获取用户指定位置

3

我正在使用谷歌地图API。

我已经成功在HTML中显示了谷歌地图。

现在,我想让用户选择位置并获取纬度/经度数据。

以下是我设想的步骤:

  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>
1个回答

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'(当用户单击时触发),最后一个函数是回调函数,它从点击事件中获取其参数。 event 参数具有名为latLng的属性,该属性是google.maps.LatLng库的实例。 同时,创建了一个标记,并且每次用户单击时其位置会改变。请参见Marker文档(https://developers.google.com/maps/documentation/javascript/reference#Marker)和一些使用教程 (https://developers.google.com/maps/documentation/javascript/markers)。
希望这可以帮到你。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接