Google Map API v3 - Centre Map on Markers

北城以北 提交于 2019-12-24 00:59:17

问题


I've recently started using Google Maps API v3.

I need to plot some locations (maybe 3 or 4) and at the same time, centre the map on these points - as opposed to manually having to set the long and lat for the map to centre on...

Can someone share some tips, or point me in the right direction?

Thanks in advance! Dan

function initialize() {
      var latlng = new google.maps.LatLng(51.50816, 0.02712);
      var myOptions = {
        zoom: 12,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      };
      var firstmap = new google.maps.Map(document.getElementById("map"),myOptions);
      //EVENT MARKER
      var point = new google.maps.LatLng(51.50816, 0.02712);
      var marker = new google.maps.Marker({
        position:point,
        map:firstmap,
        title: 'ExCel London',
        draggable:false,
        icon:'images/event.png'
      })
      var contentstring = '<div>Hello World</div>'
      var infoWindow = new google.maps.InfoWindow({
        content:contentstring
      });
      //HOTEL 1 MARKER
      var point = new google.maps.LatLng(51.503146, -0.113259);
      var marker = new google.maps.Marker({
        position:point,
        map:firstmap,
        title: 'Waterloo Hotel',
        draggable:false,
        icon:'images/flag.png'
      })
      var contentstring = '<div>Hello World</div>';
      var infoWindow = new google.maps.InfoWindow({
          content:contentstring
      });
      google.maps.event.addListener(marker,'click',function(){
          infoWindow.open(firstmap,marker);
      })
    };

回答1:


You need to save your marker on an array, and then use the function center:

function autoCenter(){
    var limits = new google.maps.LatLngBounds();
    $.each(arrayMarkers, function (index, marker){
        limits.extend(marker.position);
    });
    map.fitBounds(limits);
}


来源:https://stackoverflow.com/questions/10736653/google-map-api-v3-centre-map-on-markers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!