Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve latitude and longitude of a draggable pin via Google Maps API V3

I will explain. I managed to have a draggable pin on a map. I want to retrieve the coordinates of this point and put them into two fields: Latitude and Longitude. These coordinates will later be send to a SQL table via PHP. Here is an example of what I intend to do, but instead of several pins, it's just one and it's draggable. The problem is: I'm not even able to display the coordinates of the initial point. And of course when the user moves the pin, I want the coordinates to change as well in the fields. I hope I made myself clear. What did I do wrong? Should I use the Geocoding service?

Here goes the JS:

<script type="text/javascript">   var map;   function initialize() {   var myLatlng = new google.maps.LatLng(40.713956,-74.006653);    var myOptions = {      zoom: 8,      center: myLatlng,      mapTypeId: google.maps.MapTypeId.ROADMAP      }   map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);     var marker = new google.maps.Marker({   draggable: true,   position: myLatlng,    map: map,   title: "Your location"   });    google.maps.event.addListener(marker,'click',function(overlay,point){      document.getElementById("latbox").value = lat();      document.getElementById("lngbox").value = lng();      });  } </script>  

And the HTML:

<html> <body onload="initialize()">    <div id="map_canvas" style="width:50%; height:50%"></div>    <div id="latlong">     <p>Latitude: <input size="20" type="text" id="latbox" name="lat" ></p>     <p>Longitude: <input size="20" type="text" id="lngbox" name="lng" ></p>   </div>  </body> </html> 
like image 311
Macxim Avatar asked May 11 '11 18:05

Macxim


People also ask

How do I find the latitude and longitude of a zip code using Google API?

(We could force the locale – that the postcode is in the SG– by using"http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=POSTCODE,SG".) Simply call this url in a jquery-ajax and you will get the lat long in result.


1 Answers

Either of these work

google.maps.event.addListener(marker, 'click', function (event) {     document.getElementById("latbox").value = event.latLng.lat();     document.getElementById("lngbox").value = event.latLng.lng(); });  google.maps.event.addListener(marker, 'click', function (event) {     document.getElementById("latbox").value = this.getPosition().lat();     document.getElementById("lngbox").value = this.getPosition().lng(); }); 

You might also consider using the dragend event also

google.maps.event.addListener(marker, 'dragend', function (event) {     document.getElementById("latbox").value = this.getPosition().lat();     document.getElementById("lngbox").value = this.getPosition().lng(); }); 
like image 96
richie Avatar answered Sep 20 '22 20:09

richie