在 google 地图 javascript 单击 POI 时获取经纬度
get latitude and longitude when click POI at google map javascript
我想在点击兴趣点时获取兴趣点的经纬度。如您所见,图像底部 URL 包含兴趣点的纬度和经度。
我认为它在文档中不可用。
我记得3个月前测试的时候google map api for Android提供了POI的经纬度
为了在点击POI时得到经纬度,需要在地图对象上添加点击事件监听器。每次点击兴趣点,地图都会触发一个类型为google.maps.IconMouseEvent
:
的事件
https://developers.google.com/maps/documentation/javascript/reference/map#IconMouseEvent
您只需要检查事件是否有 placeId
字段并在必要时停止事件传播以防止默认信息 window。
查看以下示例,演示如何提取 POI 的地点 ID 和坐标。
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 41.3850639, lng: 2.1734035},
zoom: 19
});
var infowindow = new google.maps.InfoWindow();
map.addListener('click', function(event){
if (event.placeId) {
event.stop();
infowindow.close();
infowindow.setPosition(event.latLng);
infowindow.setContent(
'<div>'
+ '<strong>You clicked place</strong><br>'
+ 'Place ID: ' + event.placeId + '<br>'
+ 'Position: ' + event.latLng.lat() + ',' + event.latLng.lng() + '</div>');
infowindow.open(map);
}
});
}
#map {
height: 100%;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDztlrk_3CnzGHo7CFvLFqE_2bUKEq1JEU&callback=initMap"
async defer></script>
希望对您有所帮助!
我想在点击兴趣点时获取兴趣点的经纬度。如您所见,图像底部 URL 包含兴趣点的纬度和经度。
我认为它在文档中不可用。
我记得3个月前测试的时候google map api for Android提供了POI的经纬度
为了在点击POI时得到经纬度,需要在地图对象上添加点击事件监听器。每次点击兴趣点,地图都会触发一个类型为google.maps.IconMouseEvent
:
https://developers.google.com/maps/documentation/javascript/reference/map#IconMouseEvent
您只需要检查事件是否有 placeId
字段并在必要时停止事件传播以防止默认信息 window。
查看以下示例,演示如何提取 POI 的地点 ID 和坐标。
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 41.3850639, lng: 2.1734035},
zoom: 19
});
var infowindow = new google.maps.InfoWindow();
map.addListener('click', function(event){
if (event.placeId) {
event.stop();
infowindow.close();
infowindow.setPosition(event.latLng);
infowindow.setContent(
'<div>'
+ '<strong>You clicked place</strong><br>'
+ 'Place ID: ' + event.placeId + '<br>'
+ 'Position: ' + event.latLng.lat() + ',' + event.latLng.lng() + '</div>');
infowindow.open(map);
}
});
}
#map {
height: 100%;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDztlrk_3CnzGHo7CFvLFqE_2bUKEq1JEU&callback=initMap"
async defer></script>
希望对您有所帮助!