javascript - 获取 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
已写入地址关联的对象的最佳方法是什么?
谢谢您的帮助。
解决方案
你不需要事件,你必须使用place.geometry.location
你检索到的地方的对象。你的听众看起来像这样:
google.maps.event.addListener(autocomplete, 'place_changed', function() {
let place = this.getPlace();
let pos = place.geometry.location;
map.panTo(pos);
});
推荐阅读
- loops - 如何使用本地宏对数据进行子集化
- javascript - 如何过滤掉与Javascript中特定模式匹配的非数字字符?
- node.js - typescript/nodejs 中 process.stdin 的正确类型是什么?
- google-chrome - 如何使 conky 显示选项卡名称而不是进程名称?
- python - AttributeError:“NoneType”对象没有属性“文本”BeautifulSoup
- python - 我正在尝试使用请求在 python 中获取 cretin 类的元素
- python - 可以对 Django ORM 生成的表进行 SQL 查询吗?
- jenkins - jenkins 动态节点和 maven 设置
- python - 在图networkx列表中查找同构对
- python - 如何使用 Pandas 和 Scipy 查找数据框同一列中的两个分类变量之间的关系?