Friday, January 9, 2015

Jquery get longitude and latitude from address using google api

A little js code to retrieve long and lat from adress using google api
    function getLtLgFromAdresse(address,apiKey){
         var lng;
         var lt;
         jQuery.ajax({
                    type: "GET",
                    url: "https://maps.googleapis.com/maps/api/geocode/xml?address="+address+"&key="+apiKey,
                    dataType: "xml",
                    success: function(xml) {      
                          if(jQuery(xml).find('status').text() == 'OK'){
                              var locationNode = jQuery(xml).find('result:first'). find('geometry').find('location'); 
                              lng = locationNode.find('lng').text();
                              lt =  locationNode.find('lat').text();
                              alert("lng: "+lng+" lat:"+lt) 
                          }    else{
                                alert('Error!');          
                          }
                       
                    }                
            });
    }
apiKey is your google key, read this for more info
https://developers.google.com/maps/documentation/geocoding/

Note that here we show only the first occurence "using the :first near to the selector result.

No comments:

Post a Comment