標籤:
之前一直用百度map,但如果是國外的項目就需要用google地圖。由於在國內屏蔽了google地圖的服務,因此調用的是一個國內地址(開發用)。這個地址沒有用key,語言設定也還是中文的。
備忘:網上很多國內的例子還是用v2的介面,差異還是很大的,v3的介面感覺更加接近js的風格,很多參數都直接是json。
例子中實現了google幾個核心類的主要功能,包括:
1、在初始化時,定位到正向解析地址,這裡是定位到自由女神像;
2、在地圖中間位置初始化一個可拖拽的表徵圖,綁定拖拽結束時間,結束後通過地址逆解析,彈出一個資訊氣球;
3、在地圖上綁定滑鼠右擊事件,每個右擊事件新增一個表徵圖;
4、在地圖上綁定滑鼠雙擊事件,雙擊後地圖移動到初始位置(中間);
代碼如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head> <title></title> <script type="text/javascript" src="jquery-1.7.2.min.js"></script> <script type="text/javascript" src="https://ditu.gdgdocs.org/maps/api/js?v=3.exp&sensor=false"></script> <script type="text/javascript"> $(function() { initialize(); }); var map = null; function initialize() { var geocoder = new google.maps.Geocoder(); //地址正向解析 geocoder.geocode({ ‘address‘: ‘Liberty Island, 10004 New York Harbor‘ }, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { var myOptions = { zoom: 12, center: results[0].geometry.location, mapTypeId: google.maps.MapTypeId.ROADMAP, }; map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); //定義標示 var marker = new google.maps.Marker({ map: map, position: results[0].geometry.location, title: ‘location‘, draggable: true }); marker.setMap(map); google.maps.event.addListener(marker, "dragend", function(event) { //逆位址解析 geocoder.geocode({ ‘location‘: event.latLng }, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { var html = ‘<div>‘ + results[0].formatted_address + ‘</div>‘; var infowindow = new google.maps.InfoWindow({ content: html }); infowindow.open(map, marker); } }); //單擊後在地圖上增加一個標示 google.maps.event.addListener(map, ‘click‘, function(event) { var marker1 = new google.maps.Marker({ map: map, position: event.latLng }); marker1.setMap(map); }); //添加雙擊事件,返回地圖中央 google.maps.event.addListener(map, "dblclick", function(evvent) { var center = map.getCenter(); var lat = center.lat(); var lng = center.lng(); var latlng = new google.maps.LatLng(lat, lng); map.setCenter(latlng); }) }); } }); } </script></head><body> <div style="width: 100%; float: left;"> <div style="width: 100%; height: 660px; border: 1px solid #C0C0C0;" id="map_canvas"> </div> </div></body></html>
google map javascript api v3 例子