Google地图自动填充不会更改地图位置

时间:2015-06-29 18:23:28

标签: javascript google-maps google-maps-api-3 meteor autocomplete

您好我正在使用Meteor构建应用程序,我设法在单独的输入字段中使用谷歌地图的自动完成功能,但是当我选择一个位置时,地图不会更改为从自动完成功能中选择的位置。我正在为谷歌地图使用流星包 - dburles:google-maps。这是我的代码:

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
    });
  });
});

如何解决我如何从自动完成输入中解决并将地图链接到所选位置的问题?

1 个答案:

答案 0 :(得分:1)

您可以查看Places Auto-complete API中提供的此示例。您应该将中心设置为返回的位置。谷歌就是这样做的:

// 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.
}