Monthly Archives: February 2009

Virtual Earth point in bounding box test

I’m currently working with the Microsoft Virtual Earth SDK and wanted to test if a point is inside a box as where coordinates are specified using latitude and longitude.

It appears there are no built in function the API that does this, so this is what I came up with. Please note the special case where the bounding box overlaps the 180th degree longitude.

/**
* Returns true if point is in rectangle.
*
* @param {VELatLong} point Point to check.
* @param {VELatLongRectangle} rect Bounding box.
*/
function isPointInRect(point, rect) {
return ( (rect.TopLeftLatLong.Longitude <= rect.BottomRightLatLong.Longitude && // longitude rect.TopLeftLatLong.Longitude <= point.Longitude && rect.BottomRightLatLong.Longitude >= point.Longitude)
|| (rect.TopLeftLatLong.Longitude > rect.BottomRightLatLong.Longitude && // longitude crosses 180 degrees
rect.TopLeftLatLong.Longitude >= point.Longitude &&
rect.BottomRightLatLong.Longitude <= point.Longitude) ) && (rect.TopLeftLatLong.Latitude >= point.Latitude && // latitude
rect.BottomRightLatLong.Latitude <= point.Latitude); } [/sourcecode] This may be used, among many things, to test if a pushpin shape is within the current map view, and if it isn't the map is panned to make it visible: [sourcecode language='javascript'] var point = shape.GetPoints()[0]; if (!isPointInRect(point, map.GetMapView())) { map.PanToLatLong(point); } [/sourcecode]