vendredi 9 décembre 2011

Google Maps API2: How to find latitude and longitude (geocode) for any well formatted address.

Recently I was working on a project to develop a city guide that helps tourists live locally for any specified city in the world. One interesting feature was to propose to the user sites closer to his home based address or current location. The idea is to form a circle with a user specified radius, with center his current location or home based address. Getting the center of this circle involves getting the latitude and longitude (geocode) of the current location. The following javascript function uses the GClientGeocoder() of Google Maps API to find out accurate geographical coordinates (latitude and longitude) for any place on Earth:

1:  function getLatLng(address) {  
2:       //alert('getting the center of the circle');  
3:       if (GBrowserIsCompatible()) {  
4:             var geocoder = new GClientGeocoder();  
5:               
6:             geocoder.getLatLng(address, function(latlng) {  
7:              if (!latlng) {  
8:                  alert('"' + address + '" not found');  
9:                  return false;  
10:              } else {  
11:                  return {'Lat':latlng.lat().toFixed(6), 'Lng':latlng.lng().toFixed(6)};               
13:              }  
14:             });  
15:       }  
16:   }  

This works only for compartible browsers. You can check browser compatibility using GBrowserIsCompatible() and of course you need to include the API using
1:  <script src="http://maps.google.com/maps?file=api&v=2&key=abcdef" type="text/javascript"></script>  

Aucun commentaire:

Enregistrer un commentaire