views:

532

answers:

4

Basically whenever someones opens up my (Google) map I want it default to their approximate location.

Is there an easy way to do it with Google's API or do I have to write a custom code (this is python based app)?

+2  A: 

Check out http://www.ipinfodb.com/. You can get a latitude and longitude value by passing their services an IP address. I did something recently where I created a simple service that grabbed the current IP address and then passed it to the service ("api/location/city" is just a service that curls the ipinfodb service). Using jquery:

$.get("api/location/city", null, function(data, textStatus)
{        
    if (data != null)
    {
        if (data.Status == "OK")
        {
            var lat = parseFloat(data.Latitude);
            var lng = parseFloat(data.Longitude);

            $.setCenter(lat, lng, $.settings.defaultCityZoom);

            manager = new MarkerManager(map, {trackMarkers : true });

            var e = $.createUserMarker(map.getCenter());
            e.bindInfoWindowHtml($("#marker-content-event").html());

            var m = [];
            m.push(e);

            // map.addOverlay(e);
            manager.addMarkers(m, 10);
            manager.refresh();
        }
        else
        {
            $.setCenter($.settings.defaultLat, $.settings.defaultLng, $.settings.defaultZoom);
        }
    }
}, "json");

The key here is this line:

$.setCenter(lat, lng, $.settings.defaultCityZoom);

Just setting the center to the lat/lng of the result of the service call.

Typeoneerror
This is good but now I need to figure out how to get the IP.
Eeyore
A: 

Per the docs, just map.setCenter(new GLatLng(37.4419, -122.1419), 13); or whatever other coordinates. Doing it in the page's Javascript is normally preferred.

If you mean translating an IP to lat and long, I don't think the Google API supports that, but there are other web services that do, such as maxmind, hostip, and many, many others. I don't know which one(s) to recommend -- try out a few, would be my suggestion!

Alex Martelli
A: 

If the user uses FireFox 3.5/google gears, you can retrieve the lat and lng from the browser itself. You'll find details on another stackoverflow post here

Ryan Fernandes
+3  A: 

You can use Google API's built-in ClientLocation object:

if (GBrowserIsCompatible()) 
{   
    var map = new google.maps.Map2(document.getElementById("mapdiv"));

    if (google.loader.ClientLocation) 
    {        
        var center = new google.maps.LatLng(
            google.loader.ClientLocation.latitude,
            google.loader.ClientLocation.longitude
        );
        var zoom = 8;

        map.setCenter(center, zoom);
    }
}
Tim S. Van Haren
For some reason it doesn't work for me.
Eeyore
Works for me like charm.
zgoda