2015-04-21 37 views
3

我正在使用Google地圖API。 我成功地在html中顯示google地圖。獲取用戶指示的位置

現在,我想讓用戶選擇的位置,並獲得緯度/經度數據。

這是一步,我應該。

  1. 用戶將右鍵/左鍵點擊地圖上的某個點。
  2. 標記出現在地圖上。
  3. 用戶可以移動標記進行微調。
  4. 經度/緯度數據將顯示在文本框中。

在一般來說。

如何貫徹的宗旨是「讓用戶選擇谷歌地圖上的一個地方,並獲得地理信息」

現在我的代碼是這樣的下面,簡單地顯示在HTML

地圖
function mapInit() { 
    var centerPosition = new google.maps.LatLng(35.656956, 139.695518); 
    var option = { 
     zoom : 18, 
     center : centerPosition, 
     mapTypeId : google.maps.MapTypeId.ROADMAP 
    }; 
    var googlemap = new google.maps.Map(document.getElementById("mapField"), option); 
} 

mapInit(); 

在HTML

<div id="mapField" style="width:350px;height:350px;"></div> 

回答

2

請參閱此谷歌地圖的文檔和示例:https://developers.google.com/maps/documentation/javascript/elevation。原則上,這正是你正在尋找的。它可以進行簡化以適應您的目的。你只需要googlemap語句之後補充一點:

var marker = new google.maps.Marker({position:centerPosition, icon:icon_path}); //choose the path for the icon yourself 
google.maps.event.addListener(googlemap, 'click', function(event){ 
    //do whatever you want with this variable of the string of the clicked location: 
    event.latLng.toString(); 
    marker.setPosition(event.latLng); 
} 

這樣做是宣佈從google.maps庫一個新的事件監聽器,將其分配到地圖googlemap,聲明其類型爲'click'(它被解僱當用戶點擊時),最後的功能是一個回調,它從click事件中獲取它的參數。 event參數具有一個名爲latLng的屬性,它是google.maps.LatLng庫的一個實例。同時,創建一個標記,並且每次用戶點擊時它的位置都會改變。請參閱標記文檔(https://developers.google.com/maps/documentation/javascript/reference#Marker)和一些使用教程(https://developers.google.com/maps/documentation/javascript/markers)。

我希望這有助於