简体   繁体   中英

How to add KML-file routes to a Xamarin.Forms.Android google map?

I have some KML-files with routes that I wish to add to my map on my xamarin.forms.android project. I have created a custom renderer looking like this but now I am unsure on how to add the local kml-files (that i have in my resources folder) to the map. ( https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/custom-renderer/map/polyline-map-overlay/ )

Class:

public class CustomMap : Map
{
    public List<Position> RouteCoordinates { get; set; }

    public CustomMap()
    {
        RouteCoordinates = new List<Position>();
    }
}

Renderer:

    GoogleMap map;
    List<Position> routeCoordinates;

    protected override void OnElementChanged(Xamarin.Forms.Platform.Android.ElementChangedEventArgs<Map> e)
    {
        base.OnElementChanged(e);

        if (e.OldElement != null)
        {
            // Unsubscribe
        }

        if (e.NewElement != null)
        {
            var formsMap = (CustomMap)e.NewElement;
            routeCoordinates = formsMap.RouteCoordinates;

            ((MapView)Control).GetMapAsync(this);
        }
    }


    public void OnMapReady(GoogleMap googleMap)
    {
        map = googleMap;

        var polylineOptions = new PolylineOptions();

        polylineOptions.InvokeColor(0x66FF0000);

        foreach (var position in routeCoordinates)
        {
            polylineOptions.Add(new LatLng(position.Latitude, position.Longitude));
        }

        map.AddPolyline(polylineOptions);
    }

And this is how i use it if i want to try a route (customMap is the map i created in XAML):

customMap.RouteCoordinates.Add (new Position (37.785559, -122.396728));
customMap.RouteCoordinates.Add (new Position (37.780624, -122.390541));

But I want the KML-file to be added on the map and automatically create the route.

How would I add the KML-files to my renderer now?

You can use the Google Maps Android API Utility Library (via an Xamarin Binding library) to add/remove KML layers to your map:

The KML can be supplied as a resource id or a stream, for the work that I do I use stream from downloaded files in the cache directory:

var kmlLayer = new KmlLayer(googleMap, kmlfileStream, ApplicationContext);
kmlLayer.AddLayerToMap();

Re: https://developers.google.com/maps/documentation/android-api/utility

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM