Select to view content in your preferred language

Can KmlLayer project to Web Mercator on the fly?

964
2
09-27-2011 08:45 AM
KirkKuykendall
Deactivated User
All the kml files I've ever seen store coordinates in WGS84 coordinates.

All kml viewers I've ever seen project the coordinates to Web mercator at display time.

It seems to me that by default - or at least as an option - the KmlLayer should convert from WGS84 to web mercator behind the scenes.


Or maybe it does, and I'm just missing something?

Is this code really necessary?

void layer_Initialized(object sender, EventArgs e)
{
    var layer = sender as ESRI.ArcGIS.Client.Toolkit.DataSources.KmlLayer;
    foreach (Graphic g in layer.Graphics)
    {
        var pnt = g.Geometry as MapPoint;
        g.Geometry = ToWebMercator(pnt.X, pnt.Y);
    }
}

public static MapPoint ToWebMercator(double lon, double lat)
{
    // adapted from Oren Gal's post:
    // http://www.gal-systems.com/2011/07/convert-coordinates-between-web.html
    MapPoint pnt = new MapPoint() { SpatialReference = new SpatialReference(3857) };
    if ((Math.Abs(lon) > 180 || Math.Abs(lat) > 90))
        return pnt;

    double num = lon * 0.017453292519943295;
    double x = 6378137.0 * num;
    double a = lat * 0.017453292519943295;

    pnt.X = x;
    pnt.Y = 3189068.5 * Math.Log((1.0 + Math.Sin(a)) / (1.0 - Math.Sin(a)));
    return pnt;
}
0 Kudos
2 Replies
dotMorten_esri
Esri Notable Contributor
At this point yes, but we are working on making this a lot easier. ALso the above code can be made a lot simpler, since there's a built-in WebMercator class that will do all the math for you: ESRI.ArcGIS.Client.Projection.WebMercator
There's also this approach which cleans it up a little for you:
http://blogs.esri.com/Dev/blogs/silverlightwpf/archive/2011/02/12/Auto_2D00_reprojecting-graphics-la...
0 Kudos
KirkKuykendall
Deactivated User
Thanks Morten, I hadn't realized that client side projection is supported.  That does simplify things.  I guess the attached property can also replace IGraphic.Attributes with each KmlExtendedData in IGraphic.Attributes[extendedData] when Kml from fusion tables is added ...

var kedList = g.Attributes["extendedData"] as List<KmlExtendedData>;
if (kedList != null)
{
    g.Attributes.Clear();
    foreach (KmlExtendedData ked in kedList)
    {
        g.Attributes.Add(ked.Name, ked.Value);
    }
}    
0 Kudos