当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Google maps zoom, need to zoom near marker which is not happening instead its zooming to center point

问题描述:

i am trying to zoom my google map to a place where i push a marker on to the map.... but if i increase the zoom value in map it is zooming to the center point of map instead of the place where marker is placed... so can u please let me know... where am i going wrong... !! i tried many ways like map.setzoom and all to increase zoom near place where i push marker but its zooming to center point... please help!! here is the javascript:

 function init() {

var answers = new Array();

var data = document.getElementById('Hidden1').value;

var pairs = data.split('@');

for (var i = 0; i < pairs.length - 1; i++) {

var pair = pairs[i];

var pairs1 = pair.split(',');

answers[i] = pairs1;

}

var locations = answers;

var map = new google.maps.Map(document.getElementById('map'), {

zoom: 1,

center: new google.maps.LatLng(12.9715987, 77.5945627),

mapTypeId: google.maps.MapTypeId.ROADMAP

});

var infowindow = new google.maps.InfoWindow();

var marker, i;

for (i = 0; i < locations.length; i++) {

marker = new google.maps.Marker({

position: new google.maps.LatLng(locations[i][1], locations[i][2]),

map: map

});

google.maps.event.addListener(marker, 'click', (function(marker, i) {

return function() {

infowindow.setContent(locations[i][0]);

infowindow.open(map, marker);

}

})(marker, i));

}

map.setZoom(14);

document.getElementById('dvloading5').style.display = 'none';

document.getElementById('map').style.display = 'block';

}

the div in which i display map is a small one... and code is as follows:

 <div id="map" style="width: 485px; height: 450px">

</div>

is it because div size of map small that zoom is not happening properly?? or code issue please let me know...!! Thanking you in advance!!

网友答案:

You should use google.maps.LatLngBounds() to get the functionality.

Create a bounds variable-

var bounds = new google.maps.LatLngBounds();

Then in your loop (modified for clarity)-

for (i = 0; i < locations.length; i++) 
  {
      var lat = parseFloat(locations[i][1]);
      var lng = parseFloat(locations[i][2]);
      var pos = new google.maps.LatLng(lat, lng);
      marker = new google.maps.Marker({position: new google.maps.LatLng(pos),map: map});
      bounds.extend(pos);
   }
 map.fitBounds(bounds);
分享给朋友:
您可能感兴趣的文章:
随机阅读: