Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Maps - using geocoder to get long/lat with javascript

I'm trying to get longitude and latitude values from the google maps api with an address, however it doesn't seem to be returning any value. Is there a problem with my syntax?

var point = GClientGeocoder.getLatLng('1600 Pennsylvania Avenue NW Washington, DC 20500');
alert(point);
like image 647
Queueball Avatar asked Sep 10 '10 12:09

Queueball


People also ask

How do I find the latitude and longitude of a geocoder address?

The short story is you need to do: Geocoder geocoder = new Geocoder(this, Locale. getDefault()); List<Address> addresses = geocoder. getFromLocation(lat, lng, 1);

How do I get lat long on Google autocomplete?

Getting latitude and longitude Wen the user has selected a place we can get the latitude and longitude by calling lat() and lng() on the place object.


2 Answers

It seems like you're using v2 of Google Maps; if you're interested in using v3 (since Google has officially deprecated version 2), you could do something like this:

var mygc = new google.maps.Geocoder();
mygc.geocode({'address' : '1600 Pennsylvania Avenue NW Washington, DC 20500'}, function(results, status){
    console.log( "latitude : " + results[0].geometry.location.lat() );
    console.log( "longitude : " + results[0].geometry.location.lng() );
});

It's similar to the other examples except:

  • You call new google.maps.Geocoder() instead of GClientGeocoder()
  • You pass in an object with an 'address' property, instead of the string by itself
  • The results is a JSON object, which means you have to access lat/lng a little differently

The Google API docs have more detail for v3. Cheers!

like image 61
Christopher Scott Avatar answered Oct 25 '22 07:10

Christopher Scott


This works (provided you have the correct API key, subject to the 2500 requests/day rate limit):

address_string = '1600 Pennsylvania Avenue NW Washington, DC 20500';
geocoder = new GClientGeocoder();
geocoder.getLatLng(
    address_string,
    function(point) {
        if (point !== null) {
            alert(point); // or do whatever else with it
        } else {
            // error - not found, over limit, etc.
        }
    }
);

You seem to be calling a function of GClientGeocoder, where you need to create a new GClientGeocoder() and call its function.

like image 35
Piskvor left the building Avatar answered Oct 25 '22 06:10

Piskvor left the building