javascript 谷歌地图使用地点 ID 添加标记
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29723134/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Google Map add marker using place ID
提问by Rafty
I am trying to place a marker into Google Maps using its PlaceID. I have the map working and displaying and can also add markers (using Lattitude and Longitude) into it.
我正在尝试使用其 PlaceID 将标记放入 Google 地图。我让地图工作和显示,还可以在其中添加标记(使用纬度和经度)。
The code below is what I am using to try and make the marker display using its placeID however it is not displaying.
下面的代码是我用来尝试使用它的 placeID 显示标记的代码,但它没有显示。
function addPlaces(){
var marker = new google.maps.Marker({
place: new google.maps.Place('ChIJN1t_tDeuEmsRUsoyG83frY4'),
map: map
});
}
This function is called after the map has loaded.
在地图加载后调用此函数。
google.maps.event.addDomListener(window, "load", addPlaces);
回答by geocodezip
If you want to place a marker on the map at the place with the place_id: 'ChIJN1t_tDeuEmsRUsoyG83frY4', you need to make a getDetailsrequest to the PlaceService
如果你想在地图上放置一个标记在与place_id的地方:“ChIJN1t_tDeuEmsRUsoyG83frY4”,你需要做一个getDetails请求的PlaceService
var service = new google.maps.places.PlacesService(map);
service.getDetails({
placeId: 'ChIJN1t_tDeuEmsRUsoyG83frY4'
}, function (result, status) {
var marker = new google.maps.Marker({
map: map,
place: {
placeId: 'ChIJN1t_tDeuEmsRUsoyG83frY4',
location: result.geometry.location
}
});
});
code snippet:
代码片段:
var map;
var infoWindow;
var service;
function initialize() {
var mapOptions = {
zoom: 19,
center: new google.maps.LatLng(51.257195, 3.716563)
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
infoWindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.getDetails({
placeId: 'ChIJN1t_tDeuEmsRUsoyG83frY4'
}, function(result, status) {
if (status != google.maps.places.PlacesServiceStatus.OK) {
alert(status);
return;
}
var marker = new google.maps.Marker({
map: map,
position: result.geometry.location
});
var address = result.adr_address;
var newAddr = address.split("</span>,");
infoWindow.setContent(result.name + "<br>" + newAddr[0] + "<br>" + newAddr[1] + "<br>" + newAddr[2]);
infoWindow.open(map, marker);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map-canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?v=3&libraries=places"></script>
<div id="map-canvas"></div>