[GIS] Projecting polygon using ArcGIS API for JavaScript

arcgis-javascript-apiarcgis-servercoordinate systemgeometry-service

I have polygon data as:

POLYGON ((1645481.0939999996 6124506.9885, 1645470.0473999996
6124473.5406, 1645475.7094 6124440.1391,1645481.0939999996 6124506.9885))

in wkid=2193

I want to project this polygon using geometry service with new spatial reference wkid= 3857.

I was able to project point using similar data on new spatial reference wkid=3857, but that is not happening with polygon.

Which method should I use to project polygon using geometry service?

 function addGraphic() {

   var wkt = new Wkt.Wkt(); 
   wkt.read("POLYGON ((1645481.0939999996 6124506.9885, 1645470.0473999996   6124473.5406, 1645475.7094 6124440.1391,1645481.0939999996 6124506.9885))");
  var polygon = wkt.toObject();

  //set the spatialreference
  polygon.SpatialReference = new esri.SpatialReference({wkid: 2193});
  var outSR = new esri.SpatialReference({ wkid: 3857 });
  var gsvc = new esri.tasks.GeometryService("http://tasks.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer");

   var projPoly;
   gsvc.project([polygon], outSR, function (outGeom) {

   projPoly = outGeom[0];

   var symbol = new esri.symbol.SimpleFillSymbol().setStyle(esri.symbol.SimpleFillSymbol.STYLE_SOLID);
   var polygonGraphic = new esri.Graphic(projPoly, symbol);
   map.graphics.add(polygonGraphic);

  });
 }

Best Answer

There are two issues that you need to solve.

  • Firstly, the polygon that you have, is in a format that is called the WKT. You will have to convert it to a geometry in the ESRI's JavaScript format. I have used Wicket in the past to do this conversation for me.
  • Once you have an ESRI Polygon, you can use the project operator on the GeometryService. You should make sure that you set the spatialreference on the polygon, before you send it to the service.

You can use code similar to this:

    function projectToWebMercator() {

        var wkt = new Wkt.Wkt();
        wkt.read("POLYGON ((1645481.0939999996 6124506.9885, 1645470.0473999996 6124473.5406, 1645475.7094 6124440.1391,1645481.0939999996 6124506.9885))");
        var polygon = wkt.toObject();
        //set the spatialreference
        polygon.setSpatialReference(new SpatialReference({
                wkid : 2193
            }));

        var outSR = new SpatialReference({
                wkid : 102100
            });
        var gsvc = new GeometryService("http://tasks.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer");
        gsvc.project([polygon], outSR, function (outGeom) {
            console.dir(outGeom); //<-- Do whatever you want with the projected Polygon here
        });
    }