自动将Google地图定点居中

时间:2018-11-07 19:05:08

标签: javascript html google-maps

我有此代码:

<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>

<style>
#map_canvas {
    border:1px solid transparent;
    height: 400px;
    width: 100%;
}
</style>

<div class="col-xs-12 col-sm-12 col-md-12 col-lg-6 padding_all_right_4">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 padding_all_3">
   <h2 class="h2">Atrakcje w okolicy</h2>
</div>
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-6 padding_all_2">
   <a href ="#" class="obj-1" id="obj-1">
      <div class="apartament_atrakcje">Atrakcja 1 pl</div>
   </a>
</div>
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-6 padding_all_2">
   <a href ="#" class="obj-2" id="obj-2">
      <div class="apartament_atrakcje">Atrakcja 2 PL</div>
   </a>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 padding_all_0">
<div class="apartament_mapa">
<div id="map_canvas"></div>
<script>
   var locations = [
                                               ['Atrakcja 1 pl', 51.73925413, 19.51309225, 1],
                                               ['Atrakcja 2 PL', 53.41475000, 14.60220358, 2],
                                           ];
   var map;
   var markers = [];

   function init(){
       map = new google.maps.Map(document.getElementById('map_canvas'), {
           zoom: 10,
           center: new google.maps.LatLng(-33.92, 151.25),
           mapTypeId: google.maps.MapTypeId.ROADMAP
       });

       var num_markers = locations.length;
       for (var i = 0; i < num_markers; i++) {
           markers[i] = new google.maps.Marker({
               position: {lat:locations[i][1], lng:locations[i][2]},
               map: map,
               html: locations[i][0],
               id: i,
           });

           google.maps.event.addListener(markers[i], 'click', function(){
               var infowindow = new google.maps.InfoWindow({
                   id: this.id,
                   content:this.html,
                   position:this.getPosition()
               });
               google.maps.event.addListenerOnce(infowindow, 'closeclick', function(){
                   markers[this.id].setVisible(true);
               });
               this.setVisible(false);
               infowindow.open(map);
           });
       }
   }

   init();

</script>

该脚本在Google地图上显示2个点。 我在将地图集中在这些点上时遇到问题。目前,我在页面代码中输入了地图中心的坐标,但是地图上的点是从CMS添加的,并且必须自动对中:(

有人知道怎么做吗?

2 个答案:

答案 0 :(得分:0)

您可以使用setCenter()

map.setCenter(new google.maps.LatLng(lat, lng));

例如在第一个标记处居中

map.setCenter(new google.maps.LatLng(locations[0][1], locations[0][2]));

答案 1 :(得分:0)

您需要以一点为中心吗? scaisEdge的答案将为您做到这一点。

map.setCenter(new google.maps.LatLng(lat, lng));

否则,如果您需要以这两点的“中心”为中心。您需要计算这两个之间的中心点,然后以这个新的LatLong为中心。为此,您可以检查Google Maps Javascript API 而这个stackoverflow的帖子:Find center of multiple locations in Google Maps