简体   繁体   中英

Displaying Latitude and Longitude on Marker click event

I want to alert latitude and longitude value based on marker position. I am unable to do it.

I have recently started learning about google maps api. Please help me along.

In below code my marker is correctly moving between different location but not showing their latitude and longitude values.

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

You don't want to create a separate event for displaying the event - make it part of the code that creates (or moves) the marker, as follows:

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

Rather than using an alert , you can get a much more beautiful effect by following the links given in this answer for a really cool tooltip effect. Definitely worth taking a look - the answer links both a tutorial and a demonstration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM