Virtual Earth – Finding Multiple Locations


imageOf course, once you've found one postcode, you find yourself a reason to find lots of them as Ashley [no link] found out. You could do something like the below (which plots all the locations in postcodeArray and even labels them this time). The pushpins are added to an array before being added to the map in a single call to map.AddShape().


You need to call map.Find() sequentially. From the MSDN documentation "The callback function for this method is not re-entrant. If an application calls Find before a previous Find call has returned the search results to the callback function, the first set of arguments are destroyed and are no longer available."


In the anonymous function (in the call to map.Find()) I check if we're at the end of the array and call FindLocation() again if there are more postcodes to process. Of course these don't have to be postcodes - they could be any form of location but at least for a postcode you shouldn't need to worry about disambiguation. This technique is going to result in a deep call stack if you have a lot of locations so you'd want to refactor this code if that's the case.


It feels like there ought to be an easier way to do this as it's a common requirement. If anyone knows of one please chip in. Or if the Live team are listening....

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<script type="text/javascript"
src="http://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.1"></script>

<script type="text/javascript">
var map = null;
var postcodeLayer = null;
var pushpinArray = null;
var postcodeArray = ['RG6 1WG', 'RG1 2PY', 'RG30 2DG'];

function GetMap() {
map = new VEMap('myMap');
pushpinArray = new Array();
postcodeLayer = new VEShapeLayer();
map.LoadMap();
FindLocation(0);
}

function FindLocation(locationCount) {

try {
map.Find(null, postcodeArray[locationCount],
null, null, null, null, null, null,
false, true,

function() {
var pPin = new VEShape(VEShapeType.Pushpin, map.GetCenter());
pPin.SetTitle(postcodeArray[locationCount]);
pushpinArray[locationCount] = pPin;

if (locationCount++ < postcodeArray.length - 1) {
FindLocation(locationCount);
}
else {
map.AddShape(pushpinArray);
document.getElementById('myMap').style.visibility = 'visible';
}
}

);
}
catch (e) {
alert(e.message);
}
}

</script>

</head>
<body onload="GetMap();">
<div id='myMap' style="position: relative; width: 400px; height: 400px; visibility: hidden;">
</div>
</body>
</html>


Technorati Tags: ,

Skip to main content