一丶前言javascript
大體需求:美國地圖中標記分佈的倉庫圖釘(鼠標通過顯示地址詳情),經過輸入寄收件地郵編來在地圖上定位位置添加圖釘,將寄件地,選擇的倉庫,收件地圖釘折線相鏈接,表示大體路線。html
一丶google開發者中申請密鑰(YOUR_API_KEY)java
進入Google Developers Console建立一個Project,申請一個地圖api key,能夠設置api權限和訪問限制。git
二丶根據官方文檔先加載出地圖github
參照官方文檔,這裏官方給出的案例是異步加載的方式,可是在實際開發項目中api只能寫在引入js後面,異步加載的方式會致使調用順序而報錯,所以使用同步加載方式。ajax
1.引入在線google map jsapi
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>
三丶在地圖上建立圖釘標記async
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>