在标记点击事件上显示纬度和经度

时间:2013-07-26 19:44:47

标签: javascript jquery google-maps-api-3

我想根据标记位置提醒纬度和经度值。 我无法做到。

我最近开始学习google maps api。请帮帮我。

在下面的代码中,我的标记在不同位置之间正确移动但未显示 他们的纬度和经度值。

<html>
 <head>
<base href="<%=basePath%>">
   <style type="text/css">
      #map_canvas {
      height: 430px;
      width: 980px;
      position: static;
      top: 100px;
      left: 200px;
   }
 </style>

 <script type="text/javascript"
    src="http://maps.google.com/maps/api/js?sensor=false">
 </script>

<script type="text/javascript">
var marker;

function initialize() {
    var latlng = new google.maps.LatLng(18.9647, 72.8258);

    var myOptions = {
        zoom: 10,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        streetViewControl: false,
        mapTypeControl: false
    };

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


      google.maps.event.addListener(map, 'click', function(event) {
        placeMarker(event.latLng);
    });

    function placeMarker(location) {
        if (marker == undefined){
            marker = new google.maps.Marker({
                position: location,
                map: map,
                animation: google.maps.Animation.DROP
            });
        }
        else{
            marker.setPosition(location);
        }
        map.setCenter(location);

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

       }             

     </script>
      </head>


    <body onload="initialize()">
       <div id="map_canvas" style="1500px; 1000px"></div>
         </body>
        </html>

1 个答案:

答案 0 :(得分:2)

您不想为显示事件创建单独的事件 - 将其作为创建(或移动)标记的代码的一部分,如下所示:

function placeMarker(location) {
    if (marker == undefined){
        marker = new google.maps.Marker({
            position: location,
            map: map,
            animation: google.maps.Animation.DROP
        });
    }
    else{
        marker.setPosition(location);
    }
    map.setCenter(location);
    alert(marker.position);
}

不是使用alert,而是通过遵循this answer中给出的链接获得更加美丽的效果,以获得非常酷的工具提示效果。绝对值得一看 - 答案链接教程和演示。

相关问题