Search code examples
javascriptgoogle-mapsgeolocationyahoo-maps

Geoencode Address to GPS Coordinates


I'm looking to geoencode an address and convert it to GPS Coordinates. Basically,

var address;

//  Google/Yahoo/whatever program to convert address to GPS coordinates

var output=xx.xxxxxxx,xx.xxxxxxx

I've researched Google and Yahoo APIs, but can't seem to get their codes to work in my Google Gadget. Any suggestions?

Thanks in advance!


Solution

  • Here's what I did for my address-to-gps-coords needs:

    function get_coords(address)
    {
        var gc      = new google.maps.Geocoder(),
            opts    = { 'address' : address };
    
        gc.geocode(opts, function (results, status)
        {
            if (status == google.maps.GeocoderStatus.OK)
            {   
                var loc     = results[0].geometry.location,
                    lat     = loc.$a,
                    long    = loc.ab;
    
                // Success.  Do stuff here.
            }
            else
            {
                // Ruh roh.  Output error stuff here
            }
        });
    }
    

    Then you call it like get_coords('1600 Pennsylvania Avenue NW Washington, DC 20500') and it'll return the latitude and longitude.

    You'll need to supply your own Google Maps API key to make it work, of course.

    Hope this helps!