Google Maps API 從地址取得座標位置

在google map api想要從地址取得座標
  1. function getLatLngByAddr() {   
  2.     var geocoder = new google.maps.Geocoder();  //定義一個Geocoder物件   
  3.     geocoder.geocode(   
  4.         { address: '[地址]' },    //設定地址的字串   
  5.         function(results, status) {    //callback function   
  6.             if (status == google.maps.GeocoderStatus.OK) {    //判斷狀態   
  7.                 alert(results[0].geometry.location);             //取得座標                                   
  8.             } else {   
  9.                 alert('Error');   
  10.             }   
  11.       }   
  12.  );   
  13. }  

要各別取得經度和緯度的方法
  1. $lat=results[0].geometry.location.lat();   
  2. $lng=results[0].geometry.location.lng();   
  3.               

再改寫一下就可以再輸入表單的時候,輸入地址就取得座標位置了
  1. $("#getGeo").click(function(){   
  2.     $address=$("#address").val();   
  3.     getLatLngByAddr($address);   
  4. });   
  5.   
  6. function getLatLngByAddr($address) {   
  7.     var geocoder = new google.maps.Geocoder();    
  8.     geocoder.geocode(   
  9.         { address: $address },       
  10.         function(results, status) {      
  11.             if (status == google.maps.GeocoderStatus.OK) {      
  12.                 $lat=results[0].geometry.location.lat();   
  13.                 $("#lat").val($lat);     
  14.                 $lng=results[0].geometry.location.lng();   
  15.                 $("#lng").val($lng);                
  16.             } else {   
  17.                 alert('Error');   
  18.             }   
  19.       }   
  20.  );   
  21. }  

參考資料

Geocoding service

Google Map JavaScript API v3 的一些常用語法

留言