Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 939
shanky Avatar asked Dec 06 '25 05:12

shanky


1 Answers

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.

like image 109
Floris Avatar answered Dec 07 '25 17:12

Floris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!