我想找出地名,因此我所做的是:首先在谷歌地图上单击我从地理编码器中查找 place_id。现在,我正在将 place_id 传递给 Places API 的 PlacesService 函数。现在从那里我收到成功请求,它正在返回地点详细信息,但其名称不是正确的名称。我得到的是街道的名称。
下面是我的代码:
<script>
function initMap() {
var myLatlng = new google.maps.LatLng(37.3132072, -121.9334579);
var myOptions = {
zoom: 10,
center: myLatlng
}
var map = new google.maps.Map(document.getElementById("map"),
myOptions);
var geocoder = new google.maps.Geocoder();
google.maps.event
.addListener(
map,
'click',
function(event) {
geocoder
.geocode({
'latLng': event.latLng
},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
getname(results[0].place_id);
}
}
});
});
function getname(place_id) {
var placesService = new google.maps.places.PlacesService(map);
placesService.getDetails({
placeId: place_id
}, function(results, status) {
alert("NAME: " + results.name);
});
}
}
</script>
当我运行此代码时,我得到的结果如下:
不是获取名称(沃尔玛 super 中心),而是获取街道地址(5095 Almaden Expy)
最佳答案
如果您单击 map 上位置的“图标”,您将获得 IconMouseEvent (基本上是一个常规的 MouseEvent,并添加了 placeId
属性)。
使用该 placeId
进行请求,而不是地理编码器的返回值。
google.maps.event.addListener(map,'click', function(event) {
if (event.placeId) {
getname(event.placeId)
} else {
geocoder.geocode({'latLng': event.latLng},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
getname(results[0].place_id);
}
}
});
}
});
代码片段:
function initMap() {
var myLatlng = new google.maps.LatLng(37.329343, -121.863077);
var myOptions = {
zoom: 15,
center: myLatlng
}
var map = new google.maps.Map(document.getElementById("map"),
myOptions);
var geocoder = new google.maps.Geocoder();
google.maps.event
.addListener(
map,
'click',
function(event) {
if (event.placeId) {
getname(event.placeId)
} else {
geocoder
.geocode({
'latLng': event.latLng
},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
getname(results[0].place_id);
}
}
});
}
});
function getname(place_id) {
var placesService = new google.maps.places.PlacesService(map);
placesService.getDetails({
placeId: place_id
}, function(results, status) {
alert("NAME: " + results.name);
});
}
}
google.maps.event.addDomListener(window, "load", initMap);
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<div id="map"></div>
关于javascript - Google Places API 中的地名错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42725871/