1. 程式人生 > >基於HTML5的Geolocation獲取地理位置,配合Google Map API反向地址解析(獲取用戶真實地址)

基於HTML5的Geolocation獲取地理位置,配合Google Map API反向地址解析(獲取用戶真實地址)

add current 經緯度 cati arr offset 類型 html maps

基於HTML5的Geolocation獲取地理位置,配合Google Map API反向地址解析(獲取用戶真實地址)

html

 1 <!DOCTYPE html>
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 
 4 <head>
 5   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 6   <title>Geolocation獲取地理位置,配合Google Map API反向地址解析,
獲取當前位置並顯示在google地圖上</title> 7 <script async defer src="http://maps.google.cn/maps/api/js?key=AIzaSyBzE9xAESye6Kde-3hT-6B90nfwUkcS8Yw&callback=initMap"> 8 </script> 9 </head> 10 11 <body> 12 <div id="map" style="width: 890px; height: 640px"></div> 13 </
body> 14 15 </html>

js部分

 1   <script type="text/javascript">
 2   var geocoder;
 3   var display = "";
 4   var map;
 5 
 6   function initMap() {
 7     geocoder = new google.maps.Geocoder();
 8 
 9     if (navigator.geolocation) {
10       //獲取當前地理位置
11       navigator.geolocation.getCurrentPosition(function
(position) { 12 var coords = position.coords; 13 console.log(coords); 14 //指定一個google地圖上的坐標點,同時指定該坐標點的橫坐標和縱坐標 15 var latlng = new google.maps.LatLng(coords.latitude, coords.longitude); 16 var myOptions = { 17 zoom: 12, //設定放大倍數 18 center: latlng, //將地圖中心點設定為指定的坐標點 19 mapTypeId: google.maps.MapTypeId.ROADMAP //指定地圖類型 20 }; 21 //創建地圖,並在頁面map中顯示 22 map = new google.maps.Map(document.getElementById("map"), myOptions); 23 var marker = new google.maps.Marker({ 24 position: latlng, //將前面設定的坐標標註出來 25 map: map //將該標註設置在剛才創建的map中 26 }); 27 //地址名字解析 28 geocoder.geocode({ 29 ‘location‘: latlng //緯度/經度坐標 30 // ‘address‘: ‘南京‘ string 或者填需要解析的地名. 31 }, function(results, status) { 32 if (status == google.maps.GeocoderStatus.OK) { 33 console.log("獲取到的經緯度:"); //address_components: Array(6), formatted_address: "中國江蘇省南京市", 34 console.log(results[0]) 35 display = "地址: " + results[0].formatted_address; //格式化後的最佳匹配地址(地名可小到街道) 36 37 console.log("位置:" + display); 38 var infowindow = new google.maps.InfoWindow({ 39 content: "<span style=‘font-size:13px‘><b>經緯度: </b>" + 40 "latlng" + latlng + "<br>" + display + "</span>", 41 //坐標的偏移量 42 pixelOffset: 0, 43 position: results[0].geometry.location //GeocoderGeometry 對象 44 45 }); 46 //默認打開信息窗口,點擊也彈出信息窗口 47 infowindow.open(map, marker); 48 google.maps.event.addListener(marker, ‘click‘, function() { 49 infowindow.open(map, marker); 50 }); 51 } else { 52 alert("Geocode was not successful for the following reason: " + status); 53 } 54 }); 55 56 }, 57 function(error) { 58 //處理錯誤 59 switch (error.code) { 60 case 1: 61 alert("位置服務被拒絕。"); 62 break; 63 case 2: 64 alert("暫時獲取不到位置信息。"); 65 break; 66 case 3: 67 alert("獲取信息超時。"); 68 break; 69 default: 70 alert("未知錯誤。"); 71 break; 72 } 73 }); 74 } else { 75 alert("你的瀏覽器不支持HTML5來獲取地理位置信息。"); 76 } 77 } 78 </script>

基於HTML5的Geolocation獲取地理位置,配合Google Map API反向地址解析(獲取用戶真實地址)