使用javascript将谷歌地图缩放到所有方向的x线性英里

时间:2015-10-26 07:30:56

标签: javascript google-maps maps

我试图在中心位置的水平轴和垂直轴上显示大约X线性英里的地图。如何从谷歌地图上的中心点向北,向南,向东,向西显示10英里?

我在JavaScript下方使用以显示地图:

 function InitializeMap() {

    var latlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions =
    {
        zoom: 6,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        disableDefaultUI: false
    };


    map = new google.maps.Map(document.getElementById("map"), myOptions);

}

output map

2 个答案:

答案 0 :(得分:3)

您可以使用geometry-library计算所需区域的LatLngBounds实例,并使用fitBounds设置地图的视口:



L_PAYMENTREQUEST_n_DESCm

function InitializeMap() {

  var latlng = new google.maps.LatLng(-34.397, 150.644),
    myOptions = {
      zoom: 6,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      disableDefaultUI: false
    },


    map = new google.maps.Map(document.getElementById("map"), myOptions),
    bb = {
      n: 0,
      e: 90,
      s: 180,
      w: 270
    },
    miles = 10,
    r=miles*1609.34/2,
    b;

  for (var k in bb) {
    bb[k] = google.maps.geometry.spherical.computeOffset(latlng, r, bb[k]);
  }
  b = new google.maps.LatLngBounds(
    new google.maps.LatLng(bb.s.lat(), bb.w.lng()),
    new google.maps.LatLng(bb.n.lat(), bb.e.lng())
  );
  map.fitBounds(b);
  new google.maps.Marker({
    map: map,
    position: latlng
  });

  //the calculated area
  new google.maps.Rectangle({
    map: map,
    bounds: b
  });

}
google.maps.event.addDomListener(window, 'load', InitializeMap);

html,
body,
#map {
  height: 100%;
  margin: 0;
  padding: 0;
}




答案 1 :(得分:1)

一个选项,使用google.maps.geometry.spherical.computeOffset方法从您的"中心点"计算每个方向10英里的点。

代码段



var map;

function InitializeMap() {

  var latlng = new google.maps.LatLng(-34.397, 150.644);
  var myOptions = {
    zoom: 6,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    disableDefaultUI: false
  };


  map = new google.maps.Map(document.getElementById("map"), myOptions);
  var dist10mi = 10 * 1.60934 * 1000; // 10 miles * 1.60934 km/mi * 1000 m/km
  var north = google.maps.geometry.spherical.computeOffset(latlng, dist10mi, 0);
  var south = google.maps.geometry.spherical.computeOffset(latlng, dist10mi, 180);
  var east = google.maps.geometry.spherical.computeOffset(latlng, dist10mi, 90);
  var west = google.maps.geometry.spherical.computeOffset(latlng, dist10mi, 270);
  var bounds = new google.maps.LatLngBounds();
  bounds.extend(north);
  bounds.extend(south);
  bounds.extend(east);
  bounds.extend(west);
  map.fitBounds(bounds);
  var rectangle = new google.maps.Rectangle({
    map: map,
    bounds: bounds
  });

}
google.maps.event.addDomListener(window, "load", InitializeMap);

html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}

<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry"></script>
<div id="map"></div>
&#13;
&#13;
&#13;