我已经编写了一个代码,用于从数据库中检索数据并在google map上显示。我已经成功完成了这项工作,但是到目前为止,我无法在加载数据时缩放到标记的位置。请帮助计算这个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);
});
}
});
}
{ &#34;姓名&#34;:&#34; Ent Clinic&#34;, &#34;地址&#34;:&#34; Chandanagar&#34;, &#34; area&#34;:&#34; CHANDANAGAR&#34;, &#34;移动&#34;:&#34; 9848524297&#34;, &#34;输入&#34;:&#34; 1&#34;, &#34; center&#34;:{ &#34; lat&#34;:17.5236717, &#34; lng&#34;:78.2970363 }
答案 0 :(得分:2)
检查文件: https://developers.google.com/maps/documentation/javascript/reference 你必须使用fitBounds()方法。
在循环之前,初始化bounds变量:
var bounds = new google.maps.LatLngBounds();
在循环内部,在它的末尾,根据每个点扩展边界:
bounds.extend(marker[sd].position);
循环后(=加载所有标记后),使用fitBounds()方法:
map.fitBounds(bounds);