如何通过使用中心坐标,宽度和高度找到Google地图的边界坐标

时间:2019-01-10 13:16:12

标签: javascript google-maps

说我有一个中心坐标(1.22222,2.3333),宽25公里,高12公里。 由此,我想找到具有指定中心的边界点

1 个答案:

答案 0 :(得分:1)

打开选项是使用geometry library computeOffset method

var height = 12000; // m
var width = 25000; // m
var center = new google.maps.LatLng(1.22222, 2.3333);
var bounds = new google.maps.LatLngBounds();
var top = google.maps.geometry.spherical.computeOffset(center, height / 2, 0);
var bottom = google.maps.geometry.spherical.computeOffset(center, height / 2, 180);
var left = google.maps.geometry.spherical.computeOffset(center, width / 2, -90);
var right = google.maps.geometry.spherical.computeOffset(center, width / 2, 90);
bounds.extend(top);
bounds.extend(left);
bounds.extend(bottom);
bounds.extend(right);

proof of concept fiddle

代码段:

html,
body,
#map {
  width: 100%;
  height: 100%;
  padding: 0px;
  margin: 0px;
}
<div id="map"></div>
<script>
  function initMap() {
    var height = 12000; // m
    var width = 25000; // m
    var center = new google.maps.LatLng(1.22222, 2.3333);
    var bounds = new google.maps.LatLngBounds();
    var top = google.maps.geometry.spherical.computeOffset(center, height / 2, 0);
    var bottom = google.maps.geometry.spherical.computeOffset(center, height / 2, 180);
    var left = google.maps.geometry.spherical.computeOffset(center, width / 2, -90);
    var right = google.maps.geometry.spherical.computeOffset(center, width / 2, 90);
    bounds.extend(top);
    bounds.extend(left);
    bounds.extend(bottom);
    bounds.extend(right);
    var map = new google.maps.Map(document.getElementById('map'), {
      center: center,
      zoom: 2,
      mapTypeId: 'terrain'
    });
    var centerMarker = new google.maps.Marker({
      map: map,
      position: center
    })
    var rect = new google.maps.Rectangle({
      map: map,
      bounds: bounds
    });
    map.fitBounds(bounds);
  }
</script>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry&key= 
AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap"></script>