网页中嵌入google地图
一丶前言
大致需求:美国地图中标记分布的仓库图钉(鼠标经过显示地址详情),通过输入寄收件地邮编来在地图上定位位置添加图钉,将寄件地,选择的仓库,收件地图钉折线相连接,表示大致路线。
一丶google开发者中申请密钥(YOUR_API_KEY)
进入Google Developers Console创建一个Project,申请一个地图api key,可以设置api权限和访问限制。
二丶根据官方文档先加载出地图
参照官方文档,这里官方给出的案例是异步加载的方式,但是在实际开发项目中api只能写在引入js后面,异步加载的方式会导致调用顺序而报错,因此使用同步加载方式。
1.引入在线google map js
1 // <script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"></script> 官方异步 2 <script src="https://maps.googleapis.com/maps/api/js?key=yourkey"></script>
2.html给容器显示地图
<div id="googleMap" style="width:100%;height:380px;"></div>
3.初始化地图
1 <script> 2 // 初始化地图 3 function initialize() { 4 var mapProp = { 5 center:new google.maps.LatLng(37.09024,-95.71289100000001), 6 zoom:4, 7 mapTypeId:google.maps.MapTypeId.ROADMAP 8 }; 9 map = new google.maps.Map(document.getElementById("googleMap"), mapProp); 10 } 11 12 google.maps.event.addDomListener(window, 'load', initialize); 13 </script>
三丶在地图上创建图钉标记
1.根据坐标创建图钉
var myLatLng = {lat: -25.363, lng: 131.044}; var marker = new google.maps.Marker({ position: myLatLng, map: map, title: 'Hello World!' });
上面的是官方文档创建的,我是用了MarkerWithLabel (MarkerWithLabel extends the Google Maps JavaScript API V3)方法创建。
我是根据后台返回的仓库数组创建一个图标list,循环添加事件
1 function builderStorageMarker() { 2 $.ajax({ 3 url:'markerList.html', 4 success:function (res) { 5 warehouseList = res.data 6 for(var i=0;i<res.data.length;i++){ 7 var marker = new MarkerWithLabel({ 8 position:new google.maps.LatLng(res.data[i].longitude,res.data[i].latgitude), 9 labelContent: res.data[i].wareHouseName, 10 labelAnchor: new google.maps.Point(7, 0), 11 // labelClass: "labels", // the CSS class for the label 12 icon:'/front/img/service/position_blue.png', 13 map: map 14 }); 15 //对应的infowindow 16 marker.infowindow = new google.maps.InfoWindow({ 17 content: res.data[i].address 18 }); 19 //绑定对应的事件 20 (function(i, marker) { 21 google.maps.event.addListener( 22 marker, 23 'click', 24 function() { 25 changeColor(marker,i) 26 }) 27 marker.addListener('mouseover', function() { 28 marker.infowindow.open(map, marker); 29 }) 30 marker.addListener('mouseout', function() { 31 marker.infowindow.close(); 32 }); 33 })(i, marker) 34 makerList.push(marker) 35 } 36 } 37 }) 38 }
var marker = new MarkerWithLabel({ position:new google.maps.LatLng(-25.363,131.044), labelContent:"图钉下面的名字", labelAnchor: new google.maps.Point(7, 0), // labelClass: "labels", // the CSS class for the label icon:'图钉.png', map: map });
2.图钉绑定对应的事件
marker.addListener('mouseover', function() { marker.infowindow.open(map, marker); }) marker.addListener('mouseout', function() { marker.infowindow.close(); })
3.点击图钉改变颜色
function changeColor(maker,number) { // maker.icon = '/front/img/service/position_red.png' // maker.setMap(map) // 使用MarkerWithLabel更改icon不起作用 maker.setIcon('marker_red.png') }
四丶根据地址或者邮编获得经纬度,然后创建图钉标记位置
1 //反向地址转换(geocode()是异步函数) 2 async function zipFormatPosition(zipCode) { 3 return new Promise(resolve => { 4 geocoder.geocode({ 'address': zipCode}, function (results, status) { 5 if (status == google.maps.GeocoderStatus.OK) { 6 // var latitude = results[0].geometry.location.lat(); 7 // var longitude = results[0].geometry.location.lng(); 8 resolve(results[0].geometry.location) 9 } else { 10 $.messageBox({ 11 level: 'error', 12 message: '邮编获取地址失败,请输入正确邮编' 13 }); 14 // resolve(false) 15 } 16 }); 17 }) 18 } 19 20 zipFormatPosition("zipcode or address").then(result => { 21 var zipPosition = result; 22 if(zipPosition){ 23 var receiverPosition = new google.maps.LatLng(zipPosition.lat(),zipPosition.lng()); 24 receiverMaker = new google.maps.Marker({ 25 position:receiverPosition, 26 icon:'marker_yellow.png' 27 }); 28 receiverMaker.setMap(map); 29 } 30 })
五丶构建折线连接地址
1 var flightPlanCoordinates = [ 2 {lat: 37.772, lng: -122.214}, 3 {lat: 21.291, lng: -157.821}, 4 {lat: -18.142, lng: 178.431}, 5 {lat: -27.467, lng: 153.027} 6 ]; 7 var flightPath = new google.maps.Polyline({ 8 path: flightPlanCoordinates, 9 geodesic: true, 10 strokeColor: '#FF0000', 11 strokeOpacity: 1.0, 12 strokeWeight: 2 13 }); 14 15 flightPath.setMap(map);
六丶彩蛋:bing地图换成了Google地图(bing map变成了demo)
1 <!DOCTYPE html> 2 <html> 3 <head lang="en"> 4 <meta charset="UTF-8"> 5 <title>bing</title> 6 </head> 7 <body> 8 9 <div class="fee-est us-est" onload='GetMap();'> 10 <div>后来用google地图了,bing地图变成了demo</div> 11 </div> 12 <script> 13 //bing地图 14 function GetMap() { 15 var map = new Microsoft.Maps.Map('#myMap', { 16 credentials: 'AsXFUZiAIxemlXll9Pous5-umMjpOdiYdFALFnsLzWK6pzQOzXLYnbwVyojNFUnw ', 17 center: new Microsoft.Maps.Location(51.50632, -0.12714), 18 zoom: 10, 19 disableScrollWheelZoom:true 20 }); 21 //添加图钉 22 var center = map.getCenter(); 23 24 //Create custom Pushpin 25 var defaultColor = 'blue'; 26 var mouseDownColor = 'purple'; 27 28 var pin1 = new Microsoft.Maps.Pushpin(map.getCenter(), { 29 color: defaultColor 30 }); 31 console.log(pin1) 32 var pin2 = new Microsoft.Maps.Pushpin(new Microsoft.Maps.Location(51.50632, -0.19714), { 33 color: defaultColor 34 }); 35 36 map.entities.push(pin1); 37 map.entities.push(pin2); 38 39 Microsoft.Maps.Events.addHandler(pin1, 'mousedown', function (e) { 40 e.target.setOptions({ color: mouseDownColor }); 41 pin2.setOptions({ color: mouseDownColor }); 42 }); 43 44 } 45 </script> 46 <script type='text/javascript' 47 src='http://www.bing.com/api/maps/mapcontrol?callback=GetMap&key=YOUR_API_KEY' 48 async defer></script> 49 </body> 50 </html>