ESRI JSON to GeoJSON (for OpenLayers)
*Likely to be modified for Leaflet javascript
//create esri JSON object
var myReturn = "esriObj = "+xmlHttpGet(restCall, false);
eval(myReturn);
I can now work with esriObj as a JSON object i.e. esriObj.geometryType. What happens in the xmlHttpGet method? Basically I create a XMLHttpRequest and pass in my REST URL – your can see this code here
3. OK i have my ‘ESRI query’ JSON object now I need to parse the features in this object and essentially create GeoJSON strings which the OpenLayers sample will be happy with – cue the code butchery…
function esriDeserialize(geojson)
{
var element = document.getElementById('text');
var type = document.getElementById("formatType").value;
var features = formats['in'][type].read(geojson);
var bounds;
if(features)
{
if(features.constructor != Array) {
features = [features];
}
for(var i=0; i<features.length;>
if (!bounds) {
bounds = features[i].geometry.getBounds();
} else {
bounds.extend(features[i].geometry.getBounds());
}
}
vectors.addFeatures(features);
//map.zoomToExtent(bounds);
var plural = (features.length > 1) ? 's' : '';
//element.value = features.length + ' feature' + plural + ' added'
} else {
element.value = 'Bad input ' + type;
}
}
function getEsriGeom(restCall){
//call ESRI Rest API
//"http://pc302926/ArcGIS/rest/services/worldadmin/MapServer/0/query?text=&geometry=&geometryType=esriGeometryEnvelope&inSR=&spatialRel=esriSpatialRelIntersects&where=%22FIPS_CNTRY%22+%3D+%27AS%27&returnGeometry=true&outSR=4326&outFields=&f=json"
var element = document.getElementById('text');
//create esri JSON object
var myReturn = "esriObj = "+xmlHttpGet(restCall, false);
eval(myReturn);
element.value = "";
var coordPairsPerFeature = 0;
//for each feature
for (var i=0; i < esriObj.features.length; i++)
{
//get the geometry
var o = esriObj.features[i].geometry;
element.value = element.value + esriObj.features[i].attributes.ADMIN_NAME;
//loop through all the rings
for (var s=0; s < o.rings.length; s++)
{
//create geojson start & end - i know i'm getting polygons
var geojsonstart = '{"type":"Feature", "id":"OpenLayers.Feature.Vector_124", "properties":{}, "geometry":{"type":"Polygon", "coordinates":[['
var geojsonend = ']]}, "crs":{"type":"OGC", "properties":{"urn":"urn:ogc:def:crs:OGC:1.3:CRS84"}}}';
//the coordinates for this ring
var coords = o.rings[s];
//loop through each coordinate
var coordPair="";
for (var g=0; g < coords.length; g++)
{
coordPairsPerFeature = coordPairsPerFeature+1;
//alert(coords[g]);
if(g==coords.length-1){
coordPair = coordPair+"["+coords[g]+"]";
}else{
coordPair=coordPair+"["+coords[g]+"],";
}
}
//combine to create geojson string
esriDeserialize(geojsonstart+coordPair+geojsonend);
}
element.value = element.value + "," + coordPairsPerFeature +"n";
}
}
</features.length;>
source:
http://mapbutcher.com/blog/?p=62