我已经编写了一个代码,用于从数据库检索数据并在谷歌地图上显示。我已经成功地做到了这一点,但到目前为止,我无法在加载数据时缩放到标记的位置。请帮助计算this out.am 获取 json 格式的数据 提前致谢...
function initMap() {
// Create the map.
var infoWindow = new google.maps.InfoWindow();
var map = new google.maps.Map(document.getElementById('mapView'), {
zoom: 5,
center: {lat: 20.5937, lng: 78.9629},
mapTypeId: 'roadmap'
});
var type=document.getElementById("type1").innerHTML;
var region=document.getElementById("reg").innerHTML;
// var region=$('#reg').html();
var hq=document.getElementById("hq1").innerHTML;
var division=document.getElementById("div").innerHTML;
// alert(type);
// alert(region);
// alert(hq);
// alert(division);
$.getJSON('data.php',
{
region: region,
hq: hq,
division: division,
type:type
},
function(data){
var marker = [];
var infowindow = [];
var contentString = [];
for(var sd in data){
// alert(data);
contentString[sd] = '<div id="content">'+
'<div id="siteNotice">'+
'</div>'+
'<h1 id="firstHeading" class="firstHeading">'+data[sd].name+'</h1>'+
'<div id="bodyContent">'+
'<p><b>Address: </b>'+data[sd].address+'</p>'+
'<p><b>Area: </b>'+data[sd].area+'</p>'+
'<p><b>Mobile: </b>'+data[sd].mobile+'</p>'+
'</div>'+
'</div>';
infowindow[sd] = new google.maps.InfoWindow({
content: contentString[sd]
});
if(data[sd].type == 1){
marker[sd] = new google.maps.Marker({
icon: 'http://maps.google.com/mapfiles/ms/icons/red-dot.png',
position: data[sd].center,
map: map,
infowindow: infowindow[sd]
});
}
if(data[sd].type == 2){
marker[sd] = new google.maps.Marker({
icon: 'http://maps.google.com/mapfiles/ms/icons/red-dot.png',
position: data[sd].center,
map: map,
infowindow: infowindow[sd]
});
}
google.maps.event.addListener(marker[sd], 'click', function() {
this.infowindow.open(map, this);
// alert(this.infowindow);
});
}
});
}
{ “名称”:“耳鼻喉科诊所”, “地址”:“昌达纳加尔”, “区域”:“昌达纳加尔”, “手机”:“9848524297”, “类型”:“1”, “中心”: { “纬度”:17.5236717, “液化石油气”:78.2970363 }
最佳答案
检查文档: https://developers.google.com/maps/documentation/javascript/reference 您必须使用 fitBounds() 方法。
在循环之前,初始化边界变量:
var bounds = new google.maps.LatLngBounds();
在循环内部,在循环的末尾,根据每个点扩展边界:
bounds.extend(marker[sd].position);
循环之后(=加载所有标记之后),使用 fitBounds() 方法:
map.fitBounds(bounds);
关于javascript - 如何在加载时将 map 缩放到标记?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44603069/