raghuveer999 raghuveer999 - 2 months ago 15
Javascript Question

How to use Google Places API with a search button?

I am using Google Places API in my project. It is working fine when I give some input in a text box and hit "enter" on keyboard. It is showing results.

But, I want to place search button beside the textbox and when I press the search button, the results should be shown.

This is my initialze function.

function initialize() {
...
google.maps.event.addListener(searchBox, 'places_changed', function() {

// When I hit Enter button the execution directly comes here.
// I don't know how to work with onClick function for this purpose.

var places = searchBox.getPlaces();
for (var i = 0, marker; marker = markers[i]; i++) {
marker.setMap(null);
}
}
}

Answer

I implemented something similar recently. I needed to use two different functions; one for when places_changed is called (which already has the geolocation data, and one for when the button event is triggered which needs to manage the geolocation call to Google manually. You code might look something like this:

var searchBox, map, geocoder;

function processPlacesSearch() {
  var places = searchBox.getPlaces();
  if (places.length) {
    location = places[0].geometry.location;
    var origin = new google.maps.LatLng(location.lat(), location.lng());
    // plot origin
  }
}

function processButtonSearch(location) {
  geocoder = new google.maps.Geocoder();
  geocoder.geocode(location, function (data) {
    var lat = data[0].geometry.location.lat();
    var lng = data[0].geometry.location.lng();
    var origin = new google.maps.LatLng(lat, lng);
    // plot origin
  });
}

function initialize() {
  map = new google.maps.Map(document.getElementById('map'), options);
  searchBox = new google.maps.places.SearchBox(document.getElementById('searchbox'));
  google.maps.event.addListener(searchBox, 'places_changed', processPlacesSearch);
}

var button = document.getElementById('searchbutton');
var searchbox = document.getElementById('searchbox');

button.onclick = function () {
  var location = searchbox.value;
  processButtonSearch(location);
}
Comments