Snippets

Philip O'Gorman ArcGis KmlLayer with GroundOverlay

You are viewing an old version of this snippet. View the current version.
Revised by Philip O'Gorman 6b7821c
using SharpKml.Dom;
using SharpKml.Dom.GX;
using SharpKml.Engine;
using System;
using System.IO;

namespace FormsMapsShared.ArcGisRendering

public class TractorRenderer
    {
        Esri.ArcGISRuntime.Xamarin.Forms.MapView _mapView;
        string kmlPath = "/storage/emulated/0/SmartMaps/tractor.kml";
        public TractorRenderer(Esri.ArcGISRuntime.Xamarin.Forms.MapView mapView)
        {
            _mapView = mapView;      
        }


        public void UpdateTractorPosition(IImplement implment)
        {
            //delete the file from the last update
            if(File.Exists(kmlPath))
            {
                File.Delete(kmlPath);
            }
  
            var quad = new LatLonQuad();
            quad.Coordinates = new CoordinateCollection();
            quad.Coordinates.Add(new SharpKml.Base.Vector(implment.GraphicC1.Latitude, implment.GraphicC1.Longitude));
            quad.Coordinates.Add(new SharpKml.Base.Vector(implment.GraphicC2.Latitude, implment.GraphicC2.Longitude));
            quad.Coordinates.Add(new SharpKml.Base.Vector(implment.GraphicC3.Latitude, implment.GraphicC3.Longitude));
            quad.Coordinates.Add(new SharpKml.Base.Vector(implment.GraphicC4.Latitude, implment.GraphicC4.Longitude));

            var folder = new Folder();
            folder.Id = "f0";
            folder.Name = "Folder 0";

            var gndOverlay = new GroundOverlay();
            gndOverlay.Icon = new Icon();
            gndOverlay.Icon.Href = new Uri("tractor.png", UriKind.Relative);
            gndOverlay.GXLatLonQuad = quad;
            folder.AddFeature(gndOverlay);

            // This is the root element of the file
            Kml kml = new Kml();
            kml.Feature = folder;

            KmlFile.Create(kml, false);

            Serializer serializer = new Serializer();
            serializer.Serialize(kml);

            var stream = File.Open(kmlPath,
                FileMode.CreateNew, FileAccess.ReadWrite);

            using (var writer = new StreamWriter(stream))
            {
                writer.Write(serializer.Xml);
            }

            Uri sourceUri = new Uri(kmlPath);
            var tractorKml = new KmlLayer(sourceUri);
            tractorKml.LoadAsync();
            _mapView.Map.Basemap.BaseLayers.Clear();
            _mapView.Map.Basemap.BaseLayers.Add(tractorKml);
        }
    }
HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.