Martin
Martin

Reputation: 795

jquery geocomplete - getting users current location name

We are currently using the following jquery plugin for dropdown geo-autocomplete on a text input and it works well: http://ubilabs.github.io/geocomplete/

What we want to do however is show the users current default location in that input box before they type/select anything. Eg: Los Angeles or Sydney or London. Similar to how Facebook shows the local city name next to the map marker (which you can then click on to change it to something else)

Example of what I mean: https://i.sstatic.net/gcrRs.png (Sorry I can't paste the image in-line as <10 rep points)

Is something like this possible with the jquery geocomplete plugin or Google Maps API's Geocoding and Places Autocomplete services?

Thanks!

Upvotes: 1

Views: 2550

Answers (1)

Chris Tinsley
Chris Tinsley

Reputation: 161

You will want to combine https://developer.mozilla.org/en-US/docs/Web/API/Geolocation.getCurrentPosition

with the google places api

HTML - Loads the google places library:

...
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=places&sensor=true"></script>
<div id="google"></div>
...

Js:

...
if (navigator.geolocation) {
         navigator.geolocation.getCurrentPosition(addressToCode);
}

addressToCode = function (position,callback) {

        var service = new google.maps.places.PlacesService(document.getElementById('google'));
        var request = { query: new google.maps.LatLng(position.coords.latitude,position.coords.longitude) }
        service.textSearch(request, function (json, status) {
            if (status == google.maps.places.PlacesServiceStatus.OK) {
              //RESULTS -- DO SOMETHING HERE 
              json[0].name;
            } else {
                //alert("Geocode was not successful for the following reason: " + json.status);
            }
        });
};
...

I mentioned the GeoCoding Api, which I have had serious api limit issues with, but for reference, here is the code:

NO HTML NEEDED

JS:

  addressToCode = function (position) {
        var url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + position.coords.latitude + "," + position.coords.longitude + "&sensor=false";
        $.getJSON(url, function (json) {
            if (json.status == 'OK') {
                //DO SOMTHING HERE
                json.results[0].formatted_address;
            } else {
                //alert("Geocode was not successful for the following reason: " + json.status);
            }
        });
};

Upvotes: 2

Related Questions