如何根据placeID将谷歌地图居中,而不在地图对象中明确设置lat和lng?
我见过的所有例子都有一个值集,例如
var pyrmont = new google.maps.LatLng(-33.8665433,151.1956316);
当然你可以在一个基于ID的地方获取详细信息,然后使用lat和lng将地图居中?
function initializeGoogleMaps() {
jQuery('.site-content').prepend('<div id=\"map-container\"><div id=\"map-canvas\"></div></div>');
var request = {
placeId: 'ChIJzXBGLkQFdkgRoyT2MIxgWGw'
};
function callback(place, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
}
}
var map = new google.maps.Map(document.getElementById('map-canvas'), {
center: {
lat: 51.509526,
lng: -0.156314
},
zoom: 15
});
service = new google.maps.places.PlacesService(map);
service.getDetails(request, callback);
}
答案 0 :(得分:5)
您可以使用places服务返回的值(或标记的位置)设置地图的中心:
function callback(place, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
map.setCenter(marker.getPosition());
}
}
var map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 15
});
代码段
function initializeGoogleMaps() {
var request = {
placeId: 'ChIJzXBGLkQFdkgRoyT2MIxgWGw'
};
function callback(place, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
map.setCenter(marker.getPosition());
}
}
var map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 15
});
service = new google.maps.places.PlacesService(map);
service.getDetails(request, callback);
}
google.maps.event.addDomListener(window, 'load', initializeGoogleMaps);
&#13;
html,
body,
#map-canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
&#13;
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<div id="map-canvas"></div>
&#13;