我尝试使用getDetails()方法使用google api位置。我只需要带有数据库中引用键位置的地图。 有没有办法使用地图并直接用引用键设置位置?
当前代码:
function initialize() {
var map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(-33.8665433, 151.1956316),
zoom: 15
});
var request = {
reference: 'CqQBkQAAAJ2ovSaBhBgD-_zyhNR-T2ZzfIKlpbvRqXRYM4K2gsbKuHuGiqIYeJ8cJDmecpxjUTM28LZ3f1XmeUQXg9jxJt_sHmDmLPiWUMP9fUYUH7yyQMzeWM9GzBqRZgUs_g6ylpLBnJffvWbqTWA3ArwSeyJoSDNG7yHlsaauOW5vFIUB34l6i3Z7mDkZ0exhcQ_tMGTudsddisZ96eoT3qZfgjkSEC4k4UTdl9VEZpoK0FFewhcaFI_IrhKbeTIiOizX6HF-SkDbO8hR'
};
var infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.getDetails(request, function(place, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17);
}
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
地图正在加载第一个悉尼,在谷歌的响应后几毫秒后,地图将定位到参考密钥的位置。
我的想法是直接使用refenrence键初始化地图而不先创建地图等等...我认为我的解决方案不是最好的,有更好的方法吗?
答案 0 :(得分:1)
一种选择。使用places回调来初始化地图,在没有返回结果的情况下提供后备:
function initialize() {
var request = {
reference: 'CqQBkQAAAJ2ovSaBhBgD-_zyhNR-T2ZzfIKlpbvRqXRYM4K2gsbKuHuGiqIYeJ8cJDmecpxjUTM28LZ3f1XmeUQXg9jxJt_sHmDmLPiWUMP9fUYUH7yyQMzeWM9GzBqRZgUs_g6ylpLBnJffvWbqTWA3ArwSeyJoSDNG7yHlsaauOW5vFIUB34l6i3Z7mDkZ0exhcQ_tMGTudsddisZ96eoT3qZfgjkSEC4k4UTdl9VEZpoK0FFewhcaFI_IrhKbeTIiOizX6HF-SkDbO8hR'
};
var map = new google.maps.Map(document.getElementById('map-canvas'));
var infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.getDetails(request, function(place, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17);
}
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
} else {
// fall back if places request fails.
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(-33.8665433, 151.1956316),
zoom: 15
});
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);