Julian Samarjiev
Julian Samarjiev

Reputation: 499

Google maps autocomplete not changing map location

Hello I am building an app with Meteor and I managed to get the autocomplete feature of google maps working in a separate input field, however when I select a location, the map is not changing to the location chosen from the autocomplete feature. I am using a meteor package for google maps - dburles:google-maps. Here is my code:

map.html

<template name="map">
  <div class="map-container">
    {{> googleMap name="locations" options=locationsOptions}}
  </div>
  <div class="container">
    <div class="search">
      <form>
        <label for="location">Location</label>
        <input id="search" type="text">
      </form>
    </div>
  </div>
</template>

map.js

// Loading map on startup
Meteor.startup(function() {
  GoogleMaps.load({ key: 'my api key', libraries: 'places' });
});

Template.map.helpers({
  locationsOptions: function() {
    // Make sure the maps API has loaded
    if (GoogleMaps.loaded()) {
      // Map initialization options
      return {
        center: new google.maps.LatLng(52.524268, 13.406290),
        zoom: 12
      };
    }
  }
});

Template.map.rendered = function () {
    window.onload = function() {

        input = document.getElementById('search');
        autocomplete = new google.maps.places.Autocomplete(input);

        // When the user selects an address from the dropdown,
        google.maps.event.addListener(autocomplete, 'place_changed', function() {

             // Get the place details from the autocomplete object.
             var place = autocomplete.getPlace();

             console.log("place: " + JSON.stringify(place) );
        });
    };
};

Template.map.onCreated(function() {
  // We can use the `ready` callback to interact with the map API once the map is ready.
  GoogleMaps.ready('locations', function(map) {
    // Add a marker to the map once it's ready
    var marker = new google.maps.Marker({
      position: map.options.center,
      map: map.instance
    });
  });
});

Any ideas how I can tackle and link the map to the chosen location from the autocomplete input?

Upvotes: 0

Views: 1554

Answers (1)

kaho
kaho

Reputation: 4784

You can take a look at this example provided in the Places Auto-complete API. You should set your center to the returned location. This is how google did that:

// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
  map.fitBounds(place.geometry.viewport);
} else {
  map.setCenter(place.geometry.location);
  map.setZoom(17);  // Why 17? Because it looks good.
}

Upvotes: 1

Related Questions