To start with, it’s easiest to consider a route between a set number of existing draggable waypoints, as in the following code listing:
WordPress won’t let me embed an interactive map into a post, but you can see a static image of the map created below. Each waypoint is draggable, and the route is automatically recalculated whenever any point is moved.
Now that you’ve seen how to make a route between existing waypoints draggable, it’s relatively simple to extend this example to add additional waypoints to the route. The steps required are as follows:
- Firstly, you need to choose what action will be used to add the additional waypoint – for example: a click on the map, or a drag on the existing polyline route, etc., and define an appropriate handler to listen for this event using the Microsoft.Maps.Events.addHandler() method.
- When the event fires, create a Location object representing the coordinates of the new waypoint. To do so, convert the pixel reference passed by the event handler to a Location, using the Microsoft.Maps.Map.tryPixelToLocation() method.
- Now, you need to insert the new Location object at the appropriate position in the array of waypoints. Note that the “appropriate” position is subjective and depends on your application – you might, for example, want to allow users to sequentially define the order in which waypoints are visited (in which case, just push each new waypoint onto the end of the array, in the order they are defined), or you might allow users to choose only the location of the waypoints and use application logic to optimise the order in which they are visited (by, e.g. using the Haversine formula to determine the two closest existing waypoints in the route and insert the new Location between them). Perhaps you want different behaviours depending on whether the user clicked (and released), or if they clicked and dragged on the map. For example, consider the following existing route, and suppose the user clicked, dragged and released the mouse as shown:
The new point could be inserted into the array of waypoints between waypoints 1 and 2, since that was the position of the point on the route that was originally clicked. Or, the new waypoint could be inserted between waypoints 0 and 1, since that is the location that would optimise the generated route. Or the new waypoint could be inserted at the end of the array, after waypoint 3, since it is the last waypoint to be added to the route. It’s up to you to decide what rules to use when adding waypoints to an existing route, and where to place the new Location in the existing array of waypoints.
4. Once you’ve added the new Location(s) into the appropriate position of the waypoints array, simple call the UpdateRoute() method to request the new route and plot it on the map.