Question

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!

Was it helpful?

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!

OTHER TIPS

I did this and worked perfect:

<script type="text/javascript">
var dir1 = "5th ave, new york";
var google_url = "http://maps.googleapis.com/maps/api/geocode/json?address=";
var sensor = "&sensor=false";
var resultado;

function myFunction(){ 

    $.getJSON(
        google_url+dir1+sensor,
        function(result){
            $( "body" ).append( "Latitude: " + JSON.stringify(result.results[0].geometry.bounds.northeast.lat) )
            $( "body" ).append( "Longitude: " + JSON.stringify(result.results[0].geometry.bounds.northeast.lng) )  
    });

}

I help to maintain one API called LiveAddress which does this. Much easier to use than Google/Yahoo's APIs, and without the restrictive Terms of Service which prohibit requests en masse, storing the results, or using the data without showing a map or by automation.

Here's a complete example, using this sample wrapper function:

LiveAddress.init(123456789); // your API key here
LiveAddress.geocode("address goes here", function(geo) {
    // You can also pass in an array of addresses,
    // the ID of a DOM element containing the address,
    // or an array of IDs
    console.log(geo);
});

Individual coordinates are found in geo.lat and geo.lon, with the combined string "lat, lon" format in geo.coords. You can also obtain the precision of the data with geo.precision.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top