Desmond
Desmond

Reputation: 1736

Jquery Geocomplete. Show users current location on page load

I'm using jquery.geocomplete.js for a mobile site - I want it to load showing the users' current location on the map. The only default location options seem to be a set of fixed co-ordinates or a country name. Is it possible to show how to implement this within the Geolocation code? Here's what I have currently:

$(function(){
        var options = {
          map: ".map_canvas",              
          location: [-35.3075, 149.124417],
          mapOptions: {
            zoom: 3
          },
          zoom: 1,
          types: ['establishment'],              
          country: 'au'              
        };

        $("#geocomplete").geocomplete(options).val(); 

    });

Thanks for any help.

Upvotes: 0

Views: 4090

Answers (1)

Ohgodwhy
Ohgodwhy

Reputation: 50797

What you'll need for this, is to access the geolocation of the navigator object

if(navigator.geolocation){
    /*
     * getCurrentPosition() takes a function as a callback argument
     * The callback takes the position object returned as an argument
     */
    navigator.geolocation.getCurrentPosition(function(position){
        /**
         * pos will contain the latlng object
         * This must be passed into the setCenter instead of two float values
         */
        var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);  //
        map.setCenter(pos); //center the map based on users location
    }, function(){
        //client supports navigator object, but does not share their geolocation
    });
}else{
    //client doesn't support the navigator object
}

Of course, the above code MUST come after you instantiate the map instance.

You can read the documentation about Geolocation for Google Maps API here.

You can also see the fullscreen example here

And finally. here's a jsFiddle implementing this

Upvotes: 2

Related Questions