2014-05-12 81 views
-1

您好,我正在從w3schools學習Google Map API。我是JS新手,想將location.lat()location.lng()分配給JavaScript變量。這是教程的複製代碼。我正在嘗試將值分配爲;如何將座標值分配給JS變量

var latid=location.lat();但我認爲lat()沒有返回。

我必須在數據庫中保存座標。如果這是錯誤的方法,那麼請告訴我如何在我的數據庫中保存lnglat座標。

<!DOCTYPE html> 
<html> 
<head> 
    <script src="http://maps.googleapis.com/maps/api/js?key=mykeyishidden&sensor=false"></script> 
    <script> 
     var map; 
     var myCenter=new google.maps.LatLng(51.508742,-0.120850); 

     function initialize() { 
      var mapProp = { 
       center:myCenter, 
       zoom:5, 
       mapTypeId:google.maps.MapTypeId.ROADMAP 
      }; 

      map = new google.maps.Map(document.getElementById("googleMap"),mapProp); 

      google.maps.event.addListener(map, 'click', function(event) { 
       placeMarker(event.latLng); 
      }); 
     } 

     function placeMarker(location) { 
      var marker = new google.maps.Marker({ 
       position: location, 
       map: map, 
      }); 

      var infowindow = new google.maps.InfoWindow({ 
       content: 'Latitude: ' + location.lat() + '<br>Longitude: ' + location.lng() 
      }); 

      infowindow.open(map,marker); 
     } 

     google.maps.event.addDomListener(window, 'load', initialize); 
    </script> 
</head> 

<body> 
    <div id="googleMap" style="width:500px;height:380px;"></div> 
</body> 
</html> 
+0

這是一個客戶端腳本。沒有數據庫。 –

+1

首先,請[避免使用W3Schools](http://w3fools.com)並傳播這個詞。主要原因是他們有很多不準確和過時的信息。其次,你想要保存什麼類型的數據庫? –

+2

你在哪裏試圖將'location.lat()'賦值給一個變量 – tymeJV

回答

0

我看到您嘗試通過location.lat()訪問位置,但在整個腳本中沒有看到任何位置信息。我期待看到類似

google.maps.GeocoderGeometry.location

地方實例化。

你的目的,我覺得這是更好地嘗試以下,如果它是你的意思:

google.maps.LatLng.lat() // Returns latitude 
google.maps.LatLng.lng() // Returns longitude 
0

我跑你的網頁,看着控制檯。 在placeMarker(location)中,位置具有這些屬性。
A: -1.8017578125 k: 49.03786794532644

你的lat()和lng()實際上是返回值,而不是零!因此,舉例來說,如果你需要這些存儲在你的程序中使用的其他地方,你的代碼必須添加這些東西...

<script> 
    var map; 
    var myCenter=new google.maps.LatLng(51.508742,-0.120850); 
    var myLatLng; 
    var myLatLngs[]; 

    ... 

    function placeMarker(location) { 
      ... 

     myLatLng = {lat:location.lat(),lng:location.lng()}; 
     console.log("Lat: " + myLatLng.lat + " Lng: " + myLatLng.lng); 
     myLatLngs.push(myLatLng); 

     infowindow.open(map,marker); 
} 
... 

現在你已經得到myLatLng存儲的緯度和經度, myLatLngs是每次用戶點擊並存儲這些座標時的數組,以及一個console.log以顯示給您,以便在控制檯中進行確認。

如果你不知道如何通過看這個線程訪問瀏覽器控制檯:https://webmasters.stackexchange.com/questions/8525/how-to-open-the-javascript-console-in-different-browsers