我有以下代码(底部),它是嵌入在 php 中的 javascript,用于使用一堆标记创建我的谷歌地图。所以我想将缩放设置为能够显示所有标记的级别。我知道我需要这段代码:
var latlngbounds = new google.maps.LatLngBounds();
for (var i = 0; i < latlng.length; i++) {
latlngbounds.extend(latlng[i]);
}
map.fitBounds(latlngbounds);
要设置边界,但我不知道应该把它放在哪里,或者需要对我正在使用的代码进行哪些更改,如下所示:
$zoom = 10;
$markers = '';
$mrtallyman = 1;
foreach($locations as $location) {
$markers .= 'var myLatlng = new google.maps.LatLng'.$location[1].';
var marker'.$mrtallyman.' = new google.maps.Marker({
position: myLatlng,
map: map,
title:"'.$location[0].'",
icon: "https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld='.$mrtallyman.'|FF776B|000000",
});';
$mrtallyman++;
}
echo '
<script type="text/javascript">
function initialize() {
var userLocation = "'.$area.'";
var geocoder = new google.maps.Geocoder();
geocoder.geocode( {"address": userLocation}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latLng = results[0].geometry.location;
var mapOptions = {
center: latLng,
zoom: '.$zoom.',
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("searchPageMap"), mapOptions);
'.$markers.'
} else {
alert("Geocode failed. Reason: " + status);
}
});
}
google.maps.event.addDomListener(window, "load", initialize);
</script>';
有人可以帮我吗?
最佳答案
使用该代码的原理。
创建一个空的 google.maps.LatLngBounds 对象
var latlngbounds = new google.maps.LatLngBounds();
添加您想要显示的所有地点。它们必须是 google.maps.LatLng 对象
$markers .= 'var myLatlng = new google.maps.LatLng'.$location[1].'; latlngbounds.extend(myLatlng); var marker'.$mrtallyman.' = new google.maps.Marker({ position: myLatlng, map: map, title:"'.$location[0].'", icon: "https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld='.$mrtallyman.'|FF776B|000000", });';
将所有位置添加到边界后(在 foreach 循环右括号之后),调用 map.fitBounds
map.fitBounds(latlngbounds);
关于javascript - 谷歌地图 - 使用map.fitBounds(边界);,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19162118/