0

I'm new to using google maps and wanted to use the map to plot routes with waypoints (stopovers/other destinations within the route) on my map in Xamarin Forms. Well, at the moment I have managed to plot the routes for only two points using Google's Directions API.

You can check the code I'm using to plot the points:

  1. I sent the Origin point and the Destination Point to the Directions API using the following code:
public async Task<GoogleDirection> GetDirections(string originLatitude, string originLongitude, string destinationLatitude, string destinationLongitude)
        {
            try
            {
                GoogleDirection googleDirection = new GoogleDirection();

                var response = await client.GetAsync($"api/directions/json?mode=driving&transit_routing_preference=less_driving&origin={originLatitude},{originLongitude}&destination={destinationLatitude},{destinationLongitude}&key={AppConstants.GoogleMapsApiKey}").ConfigureAwait(false);

                if (response.IsSuccessStatusCode)
                {
                    var json = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                    if (!string.IsNullOrWhiteSpace(json))
                    {
                        googleDirection = await Task.Run(() =>
                           JsonConvert.DeserializeObject<GoogleDirection>(json)
                        ).ConfigureAwait(false);

                    }
                }

                return googleDirection;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return null;
            }

I then get the googleDirection response and formart it in the following way:

public async Task<System.Collections.Generic.List<Xamarin.Forms.GoogleMaps.Position>> LoadRoutes()
        {
            try
            {
                var googleDirection = await ApiServices.ServiceClientInstance.GetDirections(Convert.ToString(routes[0].Latitude), Convert.ToString(routes[0].Longitude), Convert.ToString(routes[1].Latitude), Convert.ToString(routes[1].Longitude));

                googleDirectionGlobal = googleDirection;

                if (googleDirection.Routes != null && googleDirection.Routes.Count > 0)
                {
                    foreach (var item in googleDirection.Routes)
                    {
                        foreach (var item2 in item.Legs)
                        {
                            RouteDistance = item2.Distance.Text;
                            RouteDuration = item2.Duration.Text;

                            var cost = item2.Distance.Value * RouteRate;

                            RouteRate = cost;
                        }
                    }

                    var positions = (Enumerable.ToList(PolylineHelper.Decode(googleDirection.Routes.First().OverviewPolyline.Points)));
                    return positions;
                }
                else
                {
                    await page.DisplayAlert("Alert", "Add your payment method inside the Google Maps console.", "Ok");
                    return null;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return null;
            }

I then use the positions returned (encoded polylines) to then plot the Polylines betweene the two points using the following code:

 map.Polylines.Clear();

                    var polyline = new Xamarin.Forms.GoogleMaps.Polyline();
                    polyline.StrokeColor = Color.FromHex("#74b6ff");
                    polyline.StrokeWidth = 8;

                    // Draw Polylines for the first time

                    var pathcontent = await mapPageViewModel.LoadRoutes();

                    foreach (var p in pathcontent)
                    {
                        polyline.Positions.Add(p);
                    }

                    map.Polylines.Add(polyline);

                    var startLocation = new Position(Convert.ToDouble(locations[0].Latitude), Convert.ToDouble(locations[0].Longitude));

                    map.MoveToRegion(MapSpan.FromCenterAndRadius(startLocation, Distance.FromMiles(0.3)));

Now, If I am to add a third and a fourth destination/waypoint, how am I to handle that. I've searched all over google but seem not to find a solution that can be applicable to my situation. Anyone, to assist me?

  • is the problem that you don't know how to request a route with multiple waypoints from the API, or that you don't know how to draw a route with multiple waypoints on the map? – Jason Sep 23 '21 at 13:06
  • I guess both @Jason, if you could assist me I'll be so greatful – Kudakwashe Mundangepfupfu Sep 23 '21 at 13:07
  • 1
    there are multiple existing questions that deal with Google Directions and multiple points, have you read them? https://www.google.com/search?q=google+maps+directions+api+multiple+points+site:stackoverflow.com – Jason Sep 23 '21 at 13:08
  • Guess let me check out the ones you have sent a link for and see if I had not come across those before – Kudakwashe Mundangepfupfu Sep 23 '21 at 13:19
  • hi @Jason, I guess I found this link https://stackoverflow.com/questions/66166463/how-to-draw-route-between-multiple-points-in-google-maps to be helpful. Thank you for your assistance – Kudakwashe Mundangepfupfu Sep 23 '21 at 20:37

0 Answers0