Prasad Sampath
Prasad Sampath

Reputation: 33

How to get the users location using google maps v3

I have been trying to get the users location using the map v3 and show the path from there location to a fixed destination. But i had no luck finding a solution to get the users location, i have read the API but couldn't figure out anything checked all the examples still the same . hope some one can help me Thanx.

Upvotes: 1

Views: 1259

Answers (3)

Asif hhh
Asif hhh

Reputation: 1552

 jQuery('#map_canvas').gmap({ 'zoom':2,'center':new google.maps.LatLng(39.809734,-98.55562), 'callback': function() {

                var self = this; 
                self.getCurrentPosition(function(position, status) { 
                    if ( status === 'OK' ) {

                        clientlat = position.coords.latitude;
                        clientlon = position.coords.longitude;
                        var clientlatlng = new google.maps.LatLng(clientlat, clientlon);

                    }
                });

          }});

Upvotes: 0

Adam Jenkins
Adam Jenkins

Reputation: 55613

google.loader.ClientLocation only gives a very approximate estimate as to the user's location.

Best choice is to use that as a fallback if HTML5 geolocation is not present, or not allowed by the user.

if(navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(
        function(p) {
        //get position from p.coords.latitude and p.coords.longitude
        },
        function() {
            //denied or error
            //use google.loader.ClientLocation
        }
    );
} else {
    //use google.loader.ClientLocation
}

Upvotes: 0

Hidden
Hidden

Reputation: 3628

Solution:

<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
function initialize() {
    var loc = {};
    var geocoder = new google.maps.Geocoder();
    if(google.loader.ClientLocation) {
        loc.lat = google.loader.ClientLocation.latitude;
        loc.lng = google.loader.ClientLocation.longitude;

        var latlng = new google.maps.LatLng(loc.lat, loc.lng);
        geocoder.geocode({'latLng': latlng}, function(results, status) {
            if(status == google.maps.GeocoderStatus.OK) {
                alert(results[0]['formatted_address']);
            };
        });
    }
}

google.load("maps", "3.x", {other_params: "sensor=false", callback:initialize});

Upvotes: 2

Related Questions