Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically input a search string and trigger places_changed for Google Maps API?

So I have a search page with a location input. If a user comes from another page with a search query, I want to programmatically input this query into the input and trigger a place changed.

Here's what I have so far:

var searchBox = new google.maps.places.SearchBox(input);

$('input#location').val(searchQuery);
google.maps.event.trigger(searchBox, 'places_changed');

However, this gives me the error Cannot read property 'length' of undefined for this line of my places_changed function:

var places = searchBox.getPlaces();

if (places.length == 0) {
  return;
}

So clearly searchBox returns undefined for getPlaces() when the input has been filled programmatically. How can I get around this?

UPDATE: Here is a JSFiddle to exemplify what I mean.

like image 821
j_d Avatar asked Mar 22 '16 15:03

j_d


1 Answers

Let's take a look what at the workflow of a SearchBox:

  1. The user types a string
  2. The API provides a list with predictions
  3. The user selects a prediction
  4. The API performs a Textsearch based on the selected prediction and returns a list of places

conclusion: When you know the searchTerm and you don't need to select a prediction, simply skip the steps 1-3 and directly run the TextSearch. Assign the returned array with places to the places-property of the SearchBox (the places_changed-event will be triggered automatically, because the SearchBox is a MVCObject, where changes of properties will be observed and the related events will be triggered automatically)

function initialize() {
        var goo = google.maps,
          map = new goo.Map(document.getElementById('map_canvas'), {
            zoom: 1,
            center: new goo.LatLng(0, 0),
            noClear: true
          }),
          input = map.getDiv().querySelector('input'),
          ac = new goo.places.SearchBox(input),
          service = new goo.places.PlacesService(map),
          win = new goo.InfoWindow,
          markers = [],
          request;


        map.controls[goo.ControlPosition.TOP_CENTER].push(input);

        if (input.value.match(/\S/)) {
          request = {
            query: input.value
          };
          if (ac.getBounds()) {
            request.bounds = ac.getBounds();
          }
          service.textSearch(request, function(places) {
            //set the places-property of the SearchBox
            //places_changed will be triggered automatically
            ac.set('places', places || [])
          });
        }

        goo.event.addListener(ac, 'places_changed', function() {
          
          win.close();
          
          //remove previous markers
          while (markers.length) {
            markers.pop().setMap(null);
          }

          //add new markers 
          (function(places) {
            var bounds = new goo.LatLngBounds();
            for (var p = 0; p < places.length; ++p) {
              markers.push((function(place) {
                bounds.extend(place.geometry.location);
                var marker = new google.maps.Marker({
                    map: map,
                    position: place.geometry.location
                  }),
                  content = document.createElement('div');
                content.appendChild(document.createElement('strong'));
                content.lastChild.appendChild(document.createTextNode(place.name));
                content.appendChild(document.createElement('div'));
                content.lastChild.appendChild(document.createTextNode(place.formatted_address));
                goo.event.addListener(marker, 'click', function() {
                  win.setContent(content);
                  win.open(map, this);
                });
                return marker;
              })(places[p]));
            };
            if (markers.length) {
              if (markers.length === 1) {
                map.setCenter(bounds.getCenter());
              } else {
                map.fitBounds(bounds);
              }
            }
          })(this.getPlaces());
        });
      }
      google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map_canvas {
  height: 100%;
  margin: 0;
  padding: 0
}
strong{
 font-weight:bold;
}
<div id="map_canvas">
  <input value="berlin">
</div>
<script src="https://maps.googleapis.com/maps/api/js?v=3&libraries=places"></script>
like image 177
Dr.Molle Avatar answered Oct 22 '22 02:10

Dr.Molle