首页 > 解决方案 > 获取 place_changed 事件的 LatLng

问题描述

我正在使用自动完成字段来搜索地址,并且我想在place_changed触发事件时检索与该地址关联的坐标,但显然我无法检索LatLng事件的对象:

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: 0,lng: 0},
    zoom: 5
  });

  let input = document.getElementById('input');
  let autocomplete = new google.maps.places.Autocomplete(input,{types: ['geocode']});
  google.maps.event.addListener(autocomplete, 'place_changed', function(event) {
    map.panTo(event.latLng);
  });
}
<script async defer src="https://maps.googleapis.com/maps/api/js?key=MY_KEY&callback=initMap&libraries=places"></script>

<div id="map" style="height: 100%;">Map here</div>

<label for="input">Search address:</label>
<input type="text" id="input">

类型错误:事件未定义

我知道这个字段主要用于自动完成,但它也允许地理编码吗?如果不是,那么检索与LatLng已写入地址关联的对象的最佳方法是什么?

谢谢您的帮助。

标签: javascriptgoogle-maps-api-3

解决方案


你不需要事件,你必须使用place.geometry.location你检索到的地方的对象。你的听众看起来像这样:

google.maps.event.addListener(autocomplete, 'place_changed', function() {
    let place = this.getPlace();
    let pos = place.geometry.location;
    map.panTo(pos);
});

推荐阅读