Using Azure Maps with a Xamarin Forms app Part 3 – Route Directions

This is the third in a three part series where I build a Xamarin Forms app that uses the Azure Maps service. You can check out the other parts here:

Part 1 – Basic text search
Part 2 – Search by Category
Part 3 – This post.  Routing

In this post I’ll show you how I was able to query the Azure Maps Route Directions Endpoint and render the route on a map.  The route directions API endpoint takes a number of parameters, of which I only use a few.  Mainly, the source location lat and long, and the destination location lat and long.  The URI I construct ends up looking like this

For this demo, I let the user choose from a few hard coded source and destination locations.  For each preconfigured source and destination, I looked up the latitude and longitude, and stored them with the option.  When the user selects from one of the source and destination pairs, I pass the associated latitude/longitude coordinates to the API.  This is just a demo, so a real solution could be more dynamic by allowing the user to query for directions based on points of interest also returned by the API.  For this post, I’m returning the route for Stanford University to Pizzeria Delfina in Palo Alto, California.  (Palo Alto is the default simulated location for the Android Emulator).  Here’s a screenshot of the view where a user selects from one of the locations.  Its just a few buttons.

Here’s the resulting route drawn as an overlay on the phone’s native map. I was able to draw the polyline overlay using this technique for Xamarin Forms Maps.

Here’s what the code looks like for when the user clicks a button and the view loads to query the API based on the hard coded choice selection and render the map. (pay no attention to the async void lol)

To start I’m using a switch statement based on the user’s selection and passing the hard coded lat long to the API. Notice I’m instantiating the map AFTER I get the results back from the query. This was because of the way the overlay is drawn on to the map for Xamarin Forms. It involves creating a custom renderer which listens to when the map is instantiated. At first, the overlay wasn’t drawing on the map because I was instantiating the map before making the API call, and the listener on the custom renderer was running and rendering the map before the results of the route query were returned. This is one of the rare cases where I personally declare UI in code, to control the declaration timing at run time. After I instantiate the map I place a pin on the starting point no matter which route is chosen. Then I place a pin on the selected destination.

So there you have it. I’ve always been a sucker for POI, mapping etc so I’m excited to be able to explore the mapping API more.

Leave a Reply