Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly get the bounding box using LocationRect.fromLocations() when locations span 180th meridian?

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.

like image 542
Cheeso Avatar asked Mar 02 '12 05:03

Cheeso


2 Answers

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

like image 100
Cheeso Avatar answered Sep 24 '22 18:09

Cheeso


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});
}
like image 23
clamchoda Avatar answered Sep 21 '22 18:09

clamchoda