Forum Xamarin.Android

Problem with path on a map

Hello to everyone, I already made a map and now I want to add the path from a location to another.

This is my code:

using System;
using System.Collections.Generic;
using System.Linq;

using Android.App;
using Android.Gms.Maps;
using Android.Gms.Maps.Model;
using Android.OS;
using Android.Locations;
using Android.Widget;
using System.Threading.Tasks;
using System.Net;
using Java.Util;
using System.Text;
using Newtonsoft.Json;

namespace AppiediAlCDN
{
[Activity()]
public class Mappa : Activity, IOnMapReadyCallback, ILocationListener
{
private GoogleMap eMap;//Map
private Button recentre;//Button
private Button route;//Button
private LatLng latlng;//Latitude and longitude of our position
private LatLng latlng2;//CDN's center
private LatLng _latlngService;//variable that contain the latitude and longitude of the service
private Marker marker1;//marker of our position
double latitudine;//latitude for the method UpdateLocation()
double longitudine;//longitude for the method UpdateLocation()
double lat_s;//variable for take the latitude of the service
double lon_s;//variable for take the longitude of the service
LocationManager locationManager;//Location Manager
string locationProvider = string.Empty;//Location Provider

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        // Create your application here
        SetContentView(Resource.Layout.mainm);

        //take arguments from the previous activity, that are the latitude and longitude of the choosen service
        lat_s = Intent.Extras.GetDouble("Latitude");
        lon_s = Intent.Extras.GetDouble("Longitude");

        //Set up the map
        SetUpMap();

        //Inizialize the location 
        InitializeLocationManager();

        //recenter button
        recentre = FindViewById<Button>(Resource.Id.recentre);
        route = FindViewById<Button>(Resource.Id.route);

        recentre.Click += recentre_Click;
        route.Click += route_Click;
    }

    public override void OnBackPressed()
    {
        eMap.Clear();
        this.Finish();
    }

    void InitializeLocationManager()
    {
        // initialise the location manager 
        locationManager = (LocationManager)GetSystemService(LocationService);
        // define its Criteria
        Criteria criteriaForLocationService = new Criteria
        {
            Accuracy = Accuracy.Coarse,
            PowerRequirement = Power.Medium
        };
        // find a location provider (GPS, wi-fi, etc.)
        IList<string> acceptableLocationProviders = locationManager.GetProviders(criteriaForLocationService, true);
        // if we have any, use the first one
        if (acceptableLocationProviders.Any())
            locationProvider = acceptableLocationProviders.First();
        else
            locationProvider = string.Empty;
    }

    public void OnLocationChanged(Location location)
    {
        //if location has changed
        if (location != null)
        {
            latitudine = location.Latitude;
            longitudine = location.Longitude;
            if (latitudine > 0 && longitudine > 0)
            {
                //if the map already exists
                if (eMap != null)
                {
                    latlng = new LatLng(latitudine, longitudine);
                    //If already exists a marker, delete it
                    if (marker1 != null)
                    {
                        marker1.Remove();
                        marker1 = null;
                    }
                    marker1 = eMap.AddMarker(new MarkerOptions().SetPosition(latlng).SetTitle("UpdateLocation").SetIcon(BitmapDescriptorFactory.FromResource(Resource.Drawable.marker_icon)));
                    //eMap.MoveCamera(CameraUpdateFactory.NewLatLngZoom(latlng2, 15.7F));
                }
                //Toast.MakeText(ApplicationContext, string.Format("UPDATE LOCATION lat => {0} long => {1}", location.Latitude, location.Longitude), ToastLength.Long).Show();
            }
        }
    } // end onLocationChanged

    protected override void OnResume()
    {
        base.OnResume();
        if (locationProvider != string.Empty)
            locationManager.RequestLocationUpdates(locationProvider, 0, 0, this);   
    } // end OnResume

    protected override void OnPause()
    {
        base.OnPause();
        locationManager.RemoveUpdates(this);
    }// end OnPause

    private void SetUpMap()
    {
        if (eMap == null)
        {
            FragmentManager.FindFragmentById<MapFragment>(Resource.Id.map).GetMapAsync(this);
        }
    }

    public void OnMapReady(GoogleMap googleMap)
    {
        eMap = googleMap;
        //latitude and longitude of the service taken from the previous activity
        _latlngService = new LatLng(lat_s,lon_s);

        //service marker
        MarkerOptions options1 = new MarkerOptions()
            .SetPosition(_latlngService)
            .SetTitle("Your Service is here")
            .SetIcon(BitmapDescriptorFactory.FromResource(Resource.Drawable.marker_service));
        eMap.AddMarker(options1);

        //CDN's center
        latlng2 = new LatLng(40.857390, 14.281000);

        //img overlay
        GroundOverlayOptions groundOverlayOptions = new GroundOverlayOptions();
        BitmapDescriptor image = BitmapDescriptorFactory.FromResource(Resource.Drawable.cdn);
        groundOverlayOptions.InvokeImage(image);
        groundOverlayOptions.Position(latlng2, 725, 450);
        groundOverlayOptions.InvokeBearing(-7.70F);
        eMap.AddGroundOverlay(groundOverlayOptions);

        //Set the firt view of the CDN
        CameraPosition INIT = new CameraPosition.Builder()
            .Target(latlng2)
            .Zoom(16.2F)
            .Bearing(82F)
            .Build();

        eMap.AnimateCamera(CameraUpdateFactory.NewCameraPosition(INIT));
    }

    public void OnStatusChanged(string provider, Availability status, Bundle extras) { }

    public void OnProviderDisabled(string provider) { }

    public void OnProviderEnabled(string provider) { }

    void recentre_Click(object sender, EventArgs e)
    {
        CameraUpdate camera = CameraUpdateFactory.NewLatLngZoom(latlng2, 16.2F);
        eMap.MoveCamera(camera);
    }

    async void route_Click(object sender, EventArgs e)
    {
        FnDrawPath(latlng, latlng2);
    }

    async Task<Address> ReverseGeocodeStartLocation()
    {
        Geocoder geocoder = new Geocoder(this);
        IList<Address> addressList =
            await geocoder.GetFromLocationAsync(latitudine, longitudine, 10);

        Address address = addressList.FirstOrDefault();
        return address;
    }

    async Task<Address> ReverseGeocodeEndLocation()
    {
        Geocoder geocoder = new Geocoder(this);
        IList<Address> addressList =
            await geocoder.GetFromLocationAsync(lat_s, lon_s, 10);

        Address address = addressList.FirstOrDefault();
        return address;
    }

    async void FnDrawPath(LatLng Source, LatLng Destination)
    {
        string strFullDirectionURL = string.Format(Utils.Constants.strGoogleDirectiongUrl, Source , Destination);
        string strJSONDirectionResponse = await FnHttpRequest(strFullDirectionURL);
        if(strJSONDirectionResponse!=Utils.Constants.strException)
        {
            FnSetDirectionQuery(strJSONDirectionResponse);
        }
        else
        {
            Toast.MakeText(this, Utils.Constants.strUnableToConnect, ToastLength.Short).Show();
        }
    }

    void FnSetDirectionQuery(string strJSONDirctionResponse)
    {
        var objRoutes = JsonConvert.DeserializeObject<GoogleDirectionClass>(strJSONDirctionResponse);
        if (objRoutes.routes.Count>0)
        {
            string encodedPoints = objRoutes.routes[0].overview_polyline.points;
            var lstDecodePoints = FnDecodePolylinePoints(encodedPoints);
            var latLngPoints = new LatLng[lstDecodePoints.Count];
            int index = 0;
            foreach(Location loc in lstDecodePoints)
            {
                latLngPoints[index++] = new LatLng(loc.Latitude,loc.Longitude);
            }
            var polylineoptions = new PolylineOptions();
            polylineoptions.InvokeColor(Android.Graphics.Color.Red);
            polylineoptions.Geodesic(true);
            polylineoptions.Add(latLngPoints);
            eMap.AddPolyline(polylineoptions);
        }
    }

    List<Location> FnDecodePolylinePoints(string encodedPoints)
    {
        if (string.IsNullOrEmpty(encodedPoints))
            return null;
        var poly = new List<Location>();
        char[] polylinechars = encodedPoints.ToCharArray();
        int index = 0;

        int currentLat = 0;
        int currentLng = 0;
        int next5bits;
        int sum;
        int shifter;

        try
        {
            while(index<polylinechars.Length)
            {
                //calculate next latitude
                sum = 0;
                shifter = 0;
                do
                {
                    next5bits = (int)polylinechars[index++] - 63;
                    sum |= (next5bits & 31) << shifter;
                    shifter += 5;
                } while (next5bits >= 32 && index < polylinechars.Length);

                if (index >= polylinechars.Length)
                    break;

                currentLat += (sum & 1) == 1 ? ~(sum >> 1) : (sum >> 1);
                //calculate nextl longitude
                sum = 0;
                shifter = 0;
                do
                {
                    next5bits = (int)polylinechars[index++] - 63;
                    sum |= (next5bits & 31) << shifter;
                    shifter += 5;
                } while (next5bits >= 32 && index < polylinechars.Length);

                if (index >= polylinechars.Length && next5bits >= 32)
                    break;

                currentLng += (sum & 1) == 1 ? ~(sum >> 1) : (sum >> 1);
                Location p = new Location("");
                p.Latitude = Convert.ToDouble(currentLat) / 100000.0;
                p.Longitude = Convert.ToDouble(currentLng) / 100000.0;
                poly.Add(p);
            }
        }
        catch
        {
              Toast.MakeText(this, Utils.Constants.strPleaseWait, ToastLength.Short).Show();
        }

        return poly;
    }

    WebClient webclient;
    async Task<string> FnHttpRequest (string strUri)
    {
        webclient = new WebClient();
        string strResultData;
        try
        {
            strResultData = await webclient.DownloadStringTaskAsync(new Uri(strUri));
            Console.WriteLine(strResultData);
        }
        catch
        {
            strResultData = Utils.Constants.strException;
        }
        finally
        {
            if(webclient!=null)
            {
                webclient.Dispose();
                webclient = null;
            }
        }
        return strResultData;
    }

}

}

But as a resoult I have this:

"geocoded_waypoints" : [{
"geocoder_status" : "ZERO_RESULTS"},
{
"geocoder_status" : "ZERO_RESULTS"
}],
"routes" : [],
"status" : "NOT_FOUND"
}
"geocoder_status" : "ZERO_RESULTS"
},
{
"geocoder_status" : "ZERO_RESULTS"
}
],
"routes" : [],
"status" : "NOT_FOUND"
}

Anyone can help me?? Thank u so much!!

All the best

Posts

  • ChristopheBERNARDChristopheBERNARD BEMember ✭✭✭✭✭

    Hello @GennaroLimite

    • first check if the API Direction is well activate
    • second put a break point into your =>strFullDirectionURL and check what it's contains

    i have a sample and for me if i type a start and a finish i have this url :
    https://maps.googleapis.com/maps/api/directions/json?origin=place+de+la+gare,+luxembourg&amp;destination=rue+de+cessange,+luxembourg&amp;key=MY GOOGLE MAPS KEY

    Have a nice coding day

  • GennaroLimiteGennaroLimite USMember ✭✭
    edited November 2016

    Hello @ChristopheBERNARD

    My strFullDirectionURL contains this: https://maps.googleapis.com/maps/api/directions/json?origin=lat/lng: (40.8555883,14.2787514)&destination=lat/lng: (40.85739,14.281)&key=MY GOOGLE MAPS KEY

    Because I give to it the coordinate of the 2 points.

  • ChristopheBERNARDChristopheBERNARD BEMember ✭✭✭✭✭

    @GennaroLimite try perhpas to copy my url and check the result

    do you have check if the API Direction is well activate on google console ?

  • GennaroLimiteGennaroLimite USMember ✭✭

    @ChristopheBERNARD with your Url it work. But how can I change the name of the route with latlng of the position?

    I already read on this: https://developers.google.com/maps/documentation/directions/intro that I can do it whit the coordinates.

  • ChristopheBERNARDChristopheBERNARD BEMember ✭✭✭✭✭

    :)
    normally you can pass the lat long but never try i think there are a mistake with the parameters ...
    i just to check on google and there are some post on stackoverflow with this question ...

    check before if you don't have some space between

    • startLat,StartLong
    • endLat,endLong

    but one question why you use the lat long ?
    why don't use the address ?

    have a nice day

  • GennaroLimiteGennaroLimite USMember ✭✭

    I use the latlng because the place where I'm building this app for is above the road. Google Maps didn't pass here because of a the Consortium that has based here. So I have to use LatLng for give the posizion on my map, but for google maps is the streed under this place. I don't know if I explain well. if you are interested look on google maps for "Centro direzionale di napoli". And check yourself.

    Thank u so much for helping me. Have a nice day

  • ChristopheBERNARDChristopheBERNARD BEMember ✭✭✭✭✭

    @GennaroLimite no problem :) ok i understand ...don't hesitate with your question !
    i spent a lot of time here, i learn a lot :)

    i love italy => beautifull contry and people are so nice and pasta what else ... :)
    And last world but its important ...Italy is the country where i see many many beautifull women of the world ...

    ciao

  • Abhir9702Abhir9702 INMember ✭✭

    can any one tell me please how to use Geodesic google maps for Xamarin.forms.. in Xamarin.Android we can able to get it by PolylineOptions as:-
    PolylineOptions poly = new PolylineOptions();
    poly.geodesic = true;

    but there is no way to allow geodesic true for Xamarin forms...

Sign In or Register to comment.