简体   繁体   English

如果只有1个标记,则Google地图会设置缩放

[英]Google Maps set zoom if only 1 marker

I have a script that gets map markers from an object and then fits the markers to the bounds. 我有一个脚本,该脚本从对象获取地图标记,然后将标记拟合到边界。 This works fin except that when the object only contains 1 marker it zooms in way to far. 除了当对象仅包含1个标记时,它会放大到很远之外,其余部分都可以正常工作。 Any suggestions on how I can set this so that if there is only on marker to set zoom to "x"; 关于如何设置此项的任何建议,以便仅在标记上将缩放设置为“ x”;

var results = [
      ['<!-- TMPL_VAR street_no --> <!-- TMPL_VAR street --> <!-- TMPL_VAR city -->, <!-- TMPL_VAR state --> <!-- TMPL_VAR zip -->',<!-- TMPL_VAR latitude -->,<!-- TMPL_VAR longitude -->]
  ];
var map;
function initMap() {
  bounds  = new google.maps.LatLngBounds();
  map = new google.maps.Map(document.getElementById('map-canvas'), {
  });
  setMarkers(map);
}
function setMarkers(map) {
  var bounds = new google.maps.LatLngBounds();
  for (var i = 0; i < results.length; i++) {
    result = results[i];
    position = new google.maps.LatLng(result[1], result[2]);
    marker = new google.maps.Marker({
      position: {lat: result[1], lng: result[2]},
      map: map,
      title: result[0]
    });
    bounds.extend(position)
  }
  map.fitBounds(bounds);
}

Your .fitBound is preventing the bound you can try this by checking it with marker length and change code as 您的.fitBound阻止了边界,您可以通过用标记长度检查它并将其更改为

if(results.length == 1) {    
      map.setZoom(5);
      map.setCenter(position)
   }



if(results.length > 1){
    map.fitBounds(bounds);
  }

So now in case of one marker map center and zoom is set instead of bounds while in case of multiple marker bounds are used ignoring the zoom and center 因此,现在在一个标记地图中心的情况下,设置缩放而不是边界,而在使用多个标记边界的情况下,忽略缩放和中心

See this CODEPEN 看到这个CODEPEN

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM