我在将地图中心设置在标记上时出现问题。我基本上想要找到一个位置并将我的地图置于其中心。这是我的代码:
<script>
var map;
function initialize() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: {lat: 51.9189046, lng: 19.1343786},
zoom: 6
});
// Search for Onninen in Lublin.
var request = {
location: map.getCenter(),
radius: '1000',
query: 'onninen lublin'
};
var service = new google.maps.places.PlacesService(map);
service.textSearch(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
var marker = new google.maps.Marker({
map: map,
place: {
placeId: results[0].place_id,
location: results[0].geometry.location
}
});
map.panTo(marker.getPosition());
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
我已经尝试了几种不同的东西。我尝试将map.center设置为marker.position我甚至尝试了一个简单的事件来查看它是否有效,但一切都崩溃了。任何帮助都会很好:)
答案 0 :(得分:0)
两件事, 1)(你可能有这个,但以防万一)你需要在网址映射api的网址调用中包含位置库
<script src="https://maps.googleapis.com/maps/api/js?libraries=places">
</script>
和2)当你创建标记时,你需要明确地给它一个位置。这是工作代码
var map;
function initialize() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: {
lat: 51.9189046,
lng: 19.1343786
},
zoom: 6
});
// Search for Onninen in Lublin.
var request = {
location: map.getCenter(),
radius: '1000',
query: 'onninen lublin'
};
var service = new google.maps.places.PlacesService(map);
service.textSearch(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
var marker = new google.maps.Marker({
map: map,
place: {
placeId: results[0].place_id,
location: results[0].geometry.location
},
position: results[0].geometry.location
});
map.panTo(marker.getPosition());
}
}
google.maps.event.addDomListener(window, 'load', initialize);
#map-canvas {
height: 300px;
width: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places">
</script>
<div id="map-canvas"></div>