如何使用LocationRect.From位置()当位置跨越180度子午线时?

I'm using the v7 Bing Maps Javascript "control" (I don't know why it's called a "control"...). I'm calling Microsoft.Maps.Map.setView({bounds: bounds}) and it isn't working as I would expect or desire.

I have a set of Polygons with points that span the 180th meridian. An example is the boundary of the islands of New Zealand - some of them are west of the 180th meridian, some portions (Chatham ISlands) are east.

When I create a polygon with those bounds and call setView(), the map zooms waaaaaay out.

enter image description here

Why? and how to avoid it?


This page provides a demonstration of the problem.

Here's the code.

var map, MM = Microsoft.Maps;

function showMap(m) {
  var options = {
    mapTypeId: MM.MapTypeId.road // aerial,
    // center will be recalculated
    // zoom will be recalculated
  },
  map1 = new MM.Map(m, options);
  return map1;
}

function doubleclickCallback(e) {
  e.handled = true;
  var bounds = map.getBounds();
  map.setView({ bounds: bounds });
}

function init() {
  var mapDiv = document.getElementById("map1");
    map = showMap(mapDiv);

  MM.Events.addHandler(map, "dblclick", doubleclickCallback); 
}

If you double click on a map that doesn't have the 180th meridian in view, nothing happens. If you double click when the map does show the 180th meridian, the map resets to zoom level 1.

#0

I looked into this.

In particular I looked in veapicore.js , version 7.0.20120123200232.91 , available at

http://ecn.dev.virtualearth.net/mapcontrol/v7.0/js/bin/7.0.20120123200232.91/en-us/veapicore.js

This module is downloaded when you include the bing maps control, like this:

<script charset="UTF-8" type="text/javascript"
        src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0">
</script>

I found what I think are two distinct problems.

• The MapMath.locationRectToMercatorZoom function (an internal function, not intended for direct use by applications) always returns a zoom of 1 when the bounding box of the LocationRect spans the 180th meridian. This is incorrect. This function is used by the Map.setView() function to auto-set the zoom, which results in the zoom waaay out phenomenon.

• The LocationRect.fromLocations() uses a naive approach for determining the bounding box for a set of locations. In fact it is not guaranteed to be a "minimum bounding box" or "minimum bounding rectangle". The box returned from that method never spans the 180th meridian, as far as I can tell. For example, the LocationRect returned for a set of locations representing the borders of the islands of New Zealand, will be start at the -176th latitude and stretch East, all the way to the +165th meridian. This is just wrong.

I fixed these problems by monkey-patching the code in veapicore.js.

function monkeyPatchMapMath() {
  Microsoft.Maps.InternalNamespaceForDelay.MapMath.
    locationRectToMercatorZoom = function (windowDimensions, bounds) {
      var ins = Microsoft.Maps.InternalNamespaceForDelay,
        d = windowDimensions,
        g = Microsoft.Maps.Globals,
        n = bounds.getNorth(),
        s = bounds.getSouth(),
        e = bounds.getEast(),
        w = bounds.getWest(),
        f = ((e+360 - w) % 360)/360,
        //f = Math.abs(w - e) / 360,
        u = Math.abs(ins.MercatorCube.latitudeToY(n) -
                     ins.MercatorCube.latitudeToY(s)),
        r = Math.min(d.width / (g.zoomOriginWidth * f),
                     d.height / (g.zoomOriginWidth * u));
      return ins.VectorMath.log2(r);
    };
}



function monkeyPatchFromLocations() {
  Microsoft.Maps.LocationRect.fromLocations = function () {
    var com = Microsoft.Maps.InternalNamespaceForDelay.Common,
      o = com.isArray(arguments[0]) ? arguments[0] : arguments,
      latMax, latMin, lngMin1, lngMin2, lngMax1, lngMax2, c,
      lngMin, lngMax, LL, dx1, dx2,
      pt = Microsoft.Maps.AltitudeReference,
      s, e, n, f = o.length;

    while (f--)
      n = o[f],
    isFinite(n.latitude) && isFinite(n.longitude) &&
      (latMax = latMax === c ? n.latitude : Math.max(latMax, n.latitude),
       latMin = latMin === c ? n.latitude : Math.min(latMin, n.latitude),
       lngMax1 = lngMax1 === c ? n.longitude : Math.max(lngMax1, n.longitude),
       lngMin1 = lngMin1 === c ? n.longitude : Math.min(lngMin1, n.longitude),
       LL = n.longitude,
       (LL < 0) && (LL += 360),
       lngMax2 = lngMax2 === c ? LL : Math.max(lngMax2, LL),
       lngMin2 = lngMin2 === c ? LL : Math.min(lngMin2, LL),
       isFinite(n.altitude) && pt.isValid(n.altitudeReference) &&
       (e = n.altitude, s = n.altitudeReference));

    dx1 = lngMax1 - lngMin1,
    dx2 = lngMax2 - lngMin2,
    lngMax = (dx1 > dx2) ? lngMax2 : lngMax1,
    lngMin = (dx1 > dx2) ? lngMin2 : lngMin1;

    return Microsoft.Maps.LocationRect.fromEdges(latMax, lngMin, latMin, lngMax, e, s);
  };
}

These functions need to be called once before use, but after loading. The first one gets delay-loaded I think, so you cannot do the monkey-patching on document ready; you need to wait until after you've created a Microsoft.Maps.Map.

The first one just does the right thing given a LocationRect. The original method flips the east and west edges in cases where the rectangle spans the 180th meridian.

The second function fixes the fromLocations method. The original implementation iterates through all locations and take the minimum longitude to be the "left" and the maximum longitude to be the "right". This fails when the minimum longitude is just to the east of the 180th meridian (say, -178), and the max longitude value is just to the west of the same line (say, +165). The resulting bounding box should span the 180th meridian but in fact the value calculated using this naive approach goes the long way around.

The corrected implementation calculates that box, and also calculates a second bounding box. For the second one, rather than using the longitude value, it uses the longitude value or the longitude + 360, when the longitude is negative. The resulting transform changes longitude from a value that ranges from -180 to 180, into a value that ranges from 0 to 360. And then the function computes the maximum and minimum of that new set of values.

The result is two bounding boxes: one with longitudes that range from -180 to +180, and another with longitudes that range from 0 to 360. These boxes will be of different widths.

The fixed implementation chooses the box with the narrower width, making a guess that the smaller box is the correct answer. This heuristic will break if you are trying to calculate the bounding box for a set of points that is larger than half the earth.

An example usage might look like this:

monkeyPatchFromLocations();
bounds = Microsoft.Maps.LocationRect.fromLocations(allPoints);
monkeyPatchMapMath();
map1.setView({bounds:bounds});

This page demonstrates: http://jsbin.com/emobav/4

Double clicking on the map never causes the zoom waaay out effect, as was seen in http://jsbin.com/emobav/2

#1

Perhaps a much more simpler approach.

bounds = Microsoft.Maps.LocationRect.fromLocations(allPoints);

LocationRect.fromLocations accepts a list of locations / array

Your polygon that you have wrapped around Australia holds a function to return an array of locations, named getLocations().

It appears one could call it like this (Double check syntax);

var viewBoundaries = Microsoft.Maps.LocationRect.fromLocations(polygon.getLocations());

                      map.setView({ bounds: viewBoundaries });
                      map.setView({ zoom: 10 });

Does this not work when spanning the 180? I don't see why it wouldn't because it's just using the points from the polygon. If so, the following could be a very simple solution for you.

You say whenever you double click the map, it pans the map. This makes total sense because you have only added an event handler to the map, and set the bounds to the boundaries of the map in the following code:

function doubleclickCallback(e) {
  e.handled = true;
  var bounds = map.getBounds();
  map.setView({ bounds: bounds });
}

MM.Events.addHandler(map, "dblclick", doubleclickCallback); 

I would think that you would need to add your click handler to the polygon in order to span the view to a specified polygon.

Microsoft.Maps.Events.addHandler(polygon, 'click', doubleclickCallback);

Then in your doubleclickCallback:

function doubleclickCallback(e) {
  // Now we are getting the boundaries of our polygon
  var bounds = e.target.getLocations();
  map.setView({ bounds: bounds });
  map.setView({ zoom: 9});
}

#2

this appears to fixed in the veapicore.js as of at least v7.0/7.0.20130619132259.11

推荐文章

显示错误信息时,禁用手风琴

显示错误信息时,禁用手风琴

推荐文章

使用JQuery可以修改数据库中的数据吗?在Asp.net?

使用JQuery可以修改数据库中的数据吗?在Asp.net?

推荐文章

在android中解析JSON对象

在android中解析JSON对象

推荐文章

卡桑德拉数据库二级指数

卡桑德拉数据库二级指数

推荐文章

ExceptionPolicyImpl类型具有多个长度为2的构造函数。无法消除歧义

ExceptionPolicyImpl类型具有多个长度为2的构造函数。无法消除歧义

推荐文章

preg_replace以在IMG tag中提出斜杠

preg_replace以在IMG tag中提出斜杠

推荐文章

如何对类型的矩阵进行元素运算scipy.sparse.csr_矩阵?

如何对类型的矩阵进行元素运算scipy.sparse.csr_矩阵?

推荐文章

IE中的大粗体(er)文本

IE中的大粗体(er)文本

推荐文章

css指针事件属性更改和相应的jquery事件未一起触发

css指针事件属性更改和相应的jquery事件未一起触发

推荐文章

我怎样才能得到所有与域相关的FB图id?

我怎样才能得到所有与域相关的FB图id?

推荐文章

我们可以从视图调用控制器的方法吗(理想情况下从helper调用)?

我们可以从视图调用控制器的方法吗(理想情况下从helper调用)?

推荐文章

为什么在启用时不应该违反外键?

为什么在启用时不应该违反外键?

推荐文章

在C中调整JPEG图像的大小会降低其分辨率

在C中调整JPEG图像的大小会降低其分辨率

推荐文章

如何在C++中初始化向量

如何在C++中初始化向量

推荐文章

android中的文本语言翻译

android中的文本语言翻译

推荐文章

如何在iphonesdk中集成twitter API,使我可以通过自己定义的UITextFields输入用户名和密码?

如何在iphonesdk中集成twitter API,使我可以通过自己定义的UITextFields输入用户名和密码?