在用户点击的任何地方显示lat lng

时间:2015-10-03 09:12:28

标签: javascript google-maps web

我想在纬度和经度中显示用户点击地图的位置(我没有使用标记事件),但它仍会显示。这是我的代码:

 var myCenter=new google.maps.LatLng(51.508742,-0.120850);

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

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

    var marker=new google.maps.Marker({
      position:myCenter,
      });

    marker.setMap(map);

    var infowindow = new google.maps.InfoWindow();

    google.maps.event.addListener(map, 'click', function(event) 
    {
    infowindow.setContent(event.LatLng.lat()+","+event.latlng.lng());
      infowindow.open(map,marker);
      });
    }

    google.maps.event.addDomListener(window, 'load', initialize);

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

试试这个,这会告诉你如何在用户点击地图时获得经度和纬度。

using

答案 1 :(得分:0)

更新标记的position - 属性以及click - 处理程序:

google.maps.event.addListener(map, 'click', function(event) 
{
  marker.setPosition(event.latLng);  
  infowindow.setContent(event.latLng.lat()+","+event.latLng.lng());
  infowindow.open(map,marker);
});

注意:它必须完全是latLng而不是LatLnglatlng

演示:

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

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

      var marker = new google.maps.Marker({
        position: myCenter,
      });

      marker.setMap(map);

      var infowindow = new google.maps.InfoWindow();

      google.maps.event.addListener(map, 'click', function(event) {
        marker.setPosition(event.latLng);
        infowindow.setContent(event.latLng.lat() + "," + event.latLng.lng());
        infowindow.open(map, marker);
      });
      
      google.maps.event.trigger(map,'click',{latLng:map.getCenter()})
    }

    google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#googleMap {
  height: 100%;
  margin: 0;
  padding: 0;
}
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3"></script>
<div id="googleMap"></div>