在用户单击的任何地方显示最新的lng



我想显示纬度和经度,用户在地图上单击他们想要的位置(我没有使用标记事件),但它仍然显示。下面是我的代码:

 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);

有人能帮忙吗?

试试这个,这将向您展示如何在用户单击地图时获取经度和纬度。

  google.maps.event.addListener(map, 'click', function( event ){
      alert( "Latitude: "+event.latLng.lat()+" "+", longitude: "+event.latLng.lng() ); 
    });

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

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>

最新更新