【问题标题】:Google maps v3 API - calculate bounds given center coordinates and distanceGoogle maps v3 API - 计算给定中心坐标和距离的边界
【发布时间】:2014-04-24 04:10:10
【问题描述】:

所以,我已经看到 this solution 了解如何计算给定中心和缩放的边界,但我正在尝试计算给定中心坐标和以英里为单位的距离的边界。

我该怎么做?

【问题讨论】:

    标签: javascript google-maps google-maps-api-3


    【解决方案1】:

    使用computeOffset 计算中心东、西距离处的一个点。将这两个点添加到 google.maps.LatLngBounds 并在该边界上调用 map.fitBounds。

    proof of concept fiddle

    代码 sn-p:

    // This example requires the Geometry library. Include the libraries=geometry
    // parameter when you first load the API. For example:
    // <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=geometry">
    function initMap() {
      var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 4,
        center: {lat: 37.04831, lng: -95.297565}
      });
      var distance = 10000; // 10 km
      var bounds = new google.maps.LatLngBounds();
      var east = google.maps.geometry.spherical.computeOffset(map.getCenter(), distance, 90);
      bounds.extend(east);
      var west = google.maps.geometry.spherical.computeOffset(map.getCenter(), distance, 270);
      bounds.extend(west);
      map.fitBounds(bounds);
      var polyline = new google.maps.Polyline({
        path: [east, west],
        map: map
      });
      var lineLength = google.maps.geometry.spherical.computeLength(polyline.getPath());
      var infowindow = new google.maps.InfoWindow();
      infowindow.setContent("line length is "+(lineLength/1000).toFixed(2)+" km");
      infowindow.setPosition(map.getCenter());
      infowindow.open(map);
    }
    /* Always set the map height explicitly to define the size of the div
     * element that contains the map. */
    #map {
      height: 100%;
    }
    
    /* Optional: Makes the sample page fill the window. */
    html,
    body {
      height: 100%;
      margin: 0;
      padding: 0;
    }
    <div id="map"></div>
    <!-- Replace the value of the key parameter with your own API key. -->
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=geometry&callback=initMap"
            async defer></script>

    【讨论】:

      猜你喜欢
      • 2011-04-16
      • 1970-01-01
      • 2015-02-18
      • 2017-04-09
      • 2011-08-28
      • 1970-01-01
      • 1970-01-01
      • 2010-12-13
      • 2010-10-27
      相关资源
      最近更新 更多