LatLngBounds - 如何获得SW和NE点数

时间:2012-06-09 00:53:47

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

我正在尝试使用Google地图的自动填充功能并将结果偏向LatLngBounds。我希望能够在一个岛屿周围绘制一个矩形(比如夏威夷群岛)并以这种方式获得LatLngBounds。我有什么工具可以帮助我吗?

2 个答案:

答案 0 :(得分:12)

很久以前我写了一个“缩放窗口”,我根据你的需要进行了调整。它只是地图和矩形听众。

http://jsfiddle.net/yV6xv/16/embedded/result/

看代码:

http://jsfiddle.net/yV6xv/16/

要使用它,请首先放大并手动平移到您的岛屿。您要选择的整个区域必须在屏幕上可见。

然后单击一次以定义矩形角。将鼠标移向对角线的对角线。 (将出现矩形选择)。再次单击以定义矩形区域。地图上方的文本区域应该为您提供具有SW和NE点的选定LatLngBounds。

在尝试包含国际日期时,它的行为并不像预期的那样。

  var map;

  var mapOptions = {
    center: new google.maps.LatLng(0.0, 0.0),
    zoom: 2,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  var bounds;
  var pt1, pt2;
  var rect;

  function toLatLng(lat, lng) {
    return new google.maps.LatLng(lat, lng);
  }

  function toBounds(j,k) {
    var pts = [];
    var latMin, latMax, lngMin, lngMax;
    var sw, ne;

    latMin = Math.min(j.lat(), k.lat());
    latMax = Math.max(j.lat(), k.lat());

    lngMin = Math.min(j.lng(), k.lng());
    lngMax = Math.max(j.lng(), k.lng());

    sw = toLatLng(latMin, lngMin);
    ne = toLatLng(latMax, lngMax);
    return new google.maps.LatLngBounds(sw, ne);
  }

  function initialize() {
    map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
    rect = new google.maps.Rectangle({
      fillColor: "#FFFF00",
      fillOpacity: 0.3,
      strokeColor: "#0000FF",
      strokeWeight: 2
    });

    // Activate the box
    google.maps.event.addListener(map, 'click', function(event) {
      pt1 = event.latLng;
      rect.setMap(map);
    });

    // Modify the box's size
    google.maps.event.addListener(map, 'mousemove', function(event) {
      if(rect.getMap() == map) {
        rect.setBounds(toBounds(pt1, event.latLng));
      }
    });

    // Remove the zoom window and zoom in
    google.maps.event.addListener(rect, 'click', function(event) {
      rect.setMap(null);
      pt2 = event.latLng;
      myBounds = toBounds(pt1, pt2);

      document.getElementById("selectedBounds").value = "new google.maps.LatLngBounds(new google.maps.LatLng" + myBounds.getSouthWest() + ", new google.maps.LatLng" + myBounds.getNorthEast() + ");";
    });

    // Allows shrinking the box
    google.maps.event.addListener(rect, 'mousemove', function(event) {
      if(rect.getMap() == map) {
        rect.setBounds(toBounds(pt1, event.latLng));
      }
    });
  }

HTML

<textarea id="selectedBounds" cols="60" rows="4"></textarea>
<div id="map_canvas"></div>​

答案 1 :(得分:0)

这是另一个与反子午线没有问题的类似工具: http://maps.forum.nu/gm_drag_polygon.html

马塞洛。