在google map api中获取点击事件的lat和lng时出错?

时间:2011-12-23 03:49:05

标签: javascript google-maps-api-3

JavaScript:

    var myLatlng = new google.maps.LatLng(10.786599576864381,106.69340372085571);  
    var myOptions = {
        zoom: 16,
        center: myLatlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }

    map = new google.maps.Map(document.getElementById("gmap"), myOptions);

    marker = new google.maps.Marker({
        position: myLatlng, 
        map: map
    });
google.maps.event.addListener(map, 'click', function() {
            var location = map.getCenter();
            document.getElementById("lat").innerHTML = location.lat();
            document.getElementById("lon").innerHTML = location.lng();
            placeMarker(location);
          });
    function placeMarker(location) {
        var clickedLocation = new google.maps.LatLng(location);
        marker.setPosition(location);
    }

HTML:

    <center>
   <div id="bd">
    <div id="gmap"></div>
     lat:<span id="lat"></span> lon:<span id="lon"></span><br/>
     </div>
    </center> 

我使用map.getCenter获取lat和lng,但结果未找到,如何修复

1 个答案:

答案 0 :(得分:1)

您获得的位置是地图的中心。

您需要通过单击来捕获事件,以便您可以像这样获取latLng:

google.maps.event.addListener(map, 'click', function(event) {
//var location = map.getCenter();
//document.getElementById("lat").innerHTML = location.lat();
//document.getElementById("lon").innerHTML = location.lng();
placeMarker(event.latLng);
})