Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add custom (get location) option to Google Autocomplete

I currently have a styled pac-input on my page for use with the Google Autocomplete from the Places Library. I've been trying to add an option for get location to the top of the drop down list but no luck.

enter image description here

Javascript (i'm no js wiz) -

  var lat = 'empty';
    var lng = 'empty';
    var placeSearch, autocomplete;
    var place;
    var geocoder;


    function initialize() {

  geocoder = new google.maps.Geocoder();
  // Create the autocomplete object, restricting the search
  // to geographical location types.
  autocomplete = new google.maps.places.Autocomplete(
      /** @type {HTMLInputElement} */(document.getElementById('pac-input')),
      { types: ['geocode', 'establishment'], 
        componentRestrictions: {country: 'GB'}});
  // When the user selects an address from the dropdown,
  // populate the address fields in the form.
  google.maps.event.addListener(autocomplete, 'place_changed', function() {
  place = autocomplete.getPlace();
      lat = place.geometry.location.lat();
      lng = place.geometry.location.lng();
      document.getElementById('please').style.display = "none";
      document.getElementById('lat').innerHTML="Latitude: " + lat + 
  "<br>Longitude: " + lng;  
  });

}


function getlocation() {
 if (navigator.geolocation)
    {
    navigator.geolocation.getCurrentPosition(showPosition);
    $('#wait').show();
    $('#getlocation').hide();

    }
  else{document.getElementById('lat').innerHTML="Geolocation is not supported by this browser.";}
  }


function showPosition(position)
  {
  lat = position.coords.latitude;
  lng = position.coords.longitude;
  var latlng = new google.maps.LatLng(lat, lng);
  geocoder.geocode({'latLng': latlng}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      if (results[0]) {
        document.getElementById('pac-input').value = (results[0].formatted_address.split(",")[0]);
      } else {
        alert('No results found');
      }
    } else {
      alert('Geocoder failed due to: ' + status);
    }
  });
  $('#wait').hide();
  $('#getlocation').show();
   document.getElementById('lat').innerHTML="Latitude: " + lat + 
  "<br>Longitude: " + lng;  
      document.getElementById('please').style.display = "none";
  }

function blurred() {
/////////bug if type and select location, click out, retype and click out. can i store the name as variable and check value against that?
  var beginning = document.getElementById('pac-input').value.split(",")[0];
  place = autocomplete.getPlace();
  if (! place) {
    lat = 'empty';
    lng = 'empty';
    document.getElementById('lat').innerHTML="Latitude: " + lat + 
  "<br>Longitude: " + lng;  
  } else {  if (! place.geometry) {
    lat = 'empty';
    lng = 'empty';
    document.getElementById('lat').innerHTML="Latitude: " + lat + 
  "<br>Longitude: " + lng;  
  }else{ if (beginning != place.name) {
    lat = 'empty';
    lng = 'empty';
    document.getElementById('lat').innerHTML="Latitude: " + lat + 
  "<br>Longitude: " + lng;  
  }}}

if (lat == 'empty') {
  document.getElementById('please').style.display = "inline-block";
}}


function focused() {
  document.getElementById('pac-input').value = "";
  if (lat != 'empty'){
  lat = 'empty';
  lng = 'empty';
}}

HTML -

 <body onload="initialize()">
    <div id="center">
    <div id="areacontainer">
      <input id="pac-input" placeholder="Area..." value=""
             onFocus="focused()" onblur="blurred()" type="text" onchange="go()">
      </input>
      <div id="getlocation" onclick="getlocation()"></div><div id="wait"></div>
    </div>
      <div id="lat"></div>
      <div id="please">Please enter a valid location.</div>
  </div>
  </body>

Thanks for any help.

like image 797
Rory Avatar asked Mar 20 '14 10:03

Rory


People also ask

How do I restrict Google Maps autocomplete to certain cities?

It is currently not possible to restrict results to a specific locality. You can use bounds as you have done so above to bias results towards, but not restricted to places contained within the specified bounds. If you believe restriction by locality would be a useful feature please file a Places API - Feature Request.


1 Answers

I realize the question is a year old and OP most certainly handled that, so this is for everyone else interested.

While one could set a handler on select's keyup to modify the options between they got received and shown up, the solution would be probably cumbersome. There is also IE issue of displaying non-DOM window for dropdown option list which might get in the way.

Instead consider using AutocompleteService to programmatically fetch predictions. It does not provide a predefined UI like Autocomplete but returns a list of results which can be modified as you like and displayed in a manner that fits your application, as a dropdown list or otherwise.

like image 84
Nic Nilov Avatar answered Sep 30 '22 11:09

Nic Nilov