Google Maps API-根据里程计算缩放

时间:2018-09-19 17:33:49

标签: javascript google-maps

如何根据输入的里程数来计算地图的缩放比例?

一个示例是用户从下拉列表中选择要在50英里半径范围内进行搜索。地图缩放级别应更新为在地图中给出的原始坐标周围显示50英里区域。

我的尝试是尽可能不准确和充实的...

calculateZoomLevel(miles) {
    let zoom = 11;

    switch(miles) {
        case 5 : {
            zoom = 14;
            break;
        }
        case 15 : {
            zoom = 13;
            break;
        }
        case 25 : {
            zoom = 11;
            break;
        }
        case 50 : {
            zoom = 10;
            break;
        }
        case 100 : {
            zoom = 8;
            break;
        }
        case 3963.2 : {
            zoom = 1
        }
    }

    return zoom;
}

1 个答案:

答案 0 :(得分:1)

最简单的选择是创建一个具有所需半径的google.maps.Circle对象,然后将地图拟合到其边界(如果不需要,您无需在地图上实际显示圆)。

var radius = parseInt(document.getElementById('radius').value, 10) * 1609.34;
circle = new google.maps.Circle({
  center: map.getCenter(),
  radius: radius,
  fillOpacity: 0.35,
  fillColor: "#FF0000",
  map: map
});

live example of a "radius search"

proof of concept fiddle (uses the geocoder to set the map center per the address entered

screenshot of resulting map       map.fitBounds(circle.getBounds());

代码段:

// global "map" variable
var map = null;
var circle = null;
var geocoder = new google.maps.Geocoder();

function initialize() {
  // create the map
  var myOptions = {
    zoom: 8,
    center: new google.maps.LatLng(43.907787, -79.359741),
  }

  map = new google.maps.Map(document.getElementById("map_canvas"),
    myOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);

function codeAddress() {
  var address = document.getElementById('address').value;
  var radius = parseInt(document.getElementById('radius').value, 10) * 1609.34;
  geocoder.geocode({
    'address': address
  }, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      side_bar_html = "";
      map.setCenter(results[0].geometry.location);
      var searchCenter = results[0].geometry.location;
      if (circle) circle.setMap(null);
      circle = new google.maps.Circle({
        center: searchCenter,
        radius: radius,
        fillOpacity: 0.35,
        fillColor: "#FF0000",
        map: map
      });
      map.fitBounds(circle.getBounds());

    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }
  });
}

var infowindow = new google.maps.InfoWindow({
  size: new google.maps.Size(150, 50)
});
html,
body {
  height: 100%;
  width: 100%;
  padding: 0px;
  margin: 0px;
}

#map_canvas {
  height: 90%;
}
<script type="text/javascript" src="http://maps.google.com/maps/api/js?libraries=geometry"></script>
<div id="map_canvas"></div>
<div>
  <input id="address" type="textbox" value="Toronto">
  <input type="button" value="Geocode" onclick="codeAddress()"><br>
  <input id="radius" type="textbox" value="50"> miles
</div>