获取标记的经度和纬度(onclick)

时间:2011-06-16 15:23:36

标签: events google-maps-api-3

如何创建标记的侦听器并获取其经度和纬度。当我为点击事件的每个标记创建一个监听器时,我可以对点击进行类似警报的操作,但是如何在点击时获得标记的坐标,即click -> this.getLat/getLng等?

3 个答案:

答案 0 :(得分:28)

试试这个:

marker = new google.maps.Marker({
             position: latlng,
             map: map                    
}); //end marker

//Add listener
google.maps.event.addListener(marker, "click", function (event) {
                    alert(this.position);
}); //end addListener

答案 1 :(得分:23)

作为Bryan Weaver的优秀答案的后续,如果你想分别保存纬度和经度,你必须使用lat()和lng()。 position属性不是常规字符串。

bryan的代码将成为:

marker = new google.maps.Marker({
             position: latlng,
             map: map                    
}); //end marker

//Add listener
google.maps.event.addListener(marker, "click", function (event) {
    var latitude = this.position.lat();
    var longitude = this.position.lng();
    alert(this.position);
}); //end addListener

您可以直接在变量(latLng)上应用lat()和lng()

    var latitude = latLng.lat();
    var longitude = latLng.lng();

答案 2 :(得分:1)

这里的所有答案都很好,

但我尝试过类似谷歌地图的作品。 当您单击地图上的某个位置时,会显示一个标记,但当您单击其他位置时,旧标记会消失,新标记会在文本字段中显示纬度和经度。

这里是DEMO     

  // In the following example, markers appear when the user clicks on the map.
  // The markers are stored in an array.
  // The user can then click an option to hide, show or delete the markers.
  var map;
  var markers = [];

  function initMap() {
    var haightAshbury = {lat: 23.2748308, lng: 77.4519248};

    map = new google.maps.Map(document.getElementById('map'), {
      zoom: 16.3,                        // Set the zoom level manually
      center: haightAshbury,
      mapTypeId: 'terrain'
    });

    // This event listener will call addMarker() when the map is clicked.
    map.addListener('click', function(event) {
      if (markers.length >= 1) {
          deleteMarkers();
      }

      addMarker(event.latLng);
      document.getElementById('lat').value = event.latLng.lat();
      document.getElementById('long').value =  event.latLng.lng();
    });
  }

  // Adds a marker to the map and push to the array.
  function addMarker(location) {
    var marker = new google.maps.Marker({
      position: location,
      map: map
    });
    markers.push(marker);
  }

  // Sets the map on all markers in the array.
  function setMapOnAll(map) {
    for (var i = 0; i < markers.length; i++) {
      markers[i].setMap(map);
    }
  }

  // Removes the markers from the map, but keeps them in the array.
  function clearMarkers() {
    setMapOnAll(null);
  }

  // Deletes all markers in the array by removing references to them.
  function deleteMarkers() {
    clearMarkers();
    markers = [];
  }
</script>
<script async defer
    src="http://maps.google.com/maps/api/js?sensor=false&callback=initMap">
</script>

所以这段代码的作用是,当你点击地图上的某个地方时,纬度和经度的值会显示在文本字段中。