0

I am getting a response JSON from a service and I need to parse it and use the geometry from it to render on a map using OL2.

JSON format:

{"abc":{"def":[{"ghj":5,"cvb":"m",

"geometry":{

"type":"MultiPolygon","coordinates":[[[[-77.09261699781653,38.87124716098509],[-77.09261699781653,38.87125044082939],[-77.09262121055383,38.87125044082939],[-77.09262121055383,38.87126028036227],[-77.09261699781653,38.87126028036227],[-77.09261699781653,38.87126356020657],[-77.09262121055383,38.87126356020657],[-77.09262121055383,38.87127667958376],[-77.09261278507921,38.871279959428044],[-77.09261278507921,38.87127667958376],[-77.09260857234192,38.87127667958376],[-77.09260857234192,38.87126356020657],[-77.0926001468673,38.87126028036227],[-77.0926001468673,38.87125044082939],[-77.09261699781653,38.87124716098509]]]],"crs":{"type":"name","properties":{"name":"epsg:4326"}}

}

}]}}

OL2 code:

var featurecollection = {
              "type": "FeatureCollection", 
              "features": [
                {
            "type": "Feature",
            "geometry": {
response.abc.def[0].geometry

        }
              ]
           };
           var geojson_format = new OpenLayers.Format.GeoJSON();
           var vector_layer = new OpenLayers.Layer.Vector(); 
           map.addLayer(vector_layer);
           vector_layer.addFeatures(geojson_format.read(featurecollection));

        }

what I am doing wrong or how to do it in right way?

EDIT: Entire file as follows:

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <link rel="stylesheet" href="http://openlayers.org/dev/theme/default/style.css" type="text/css">
    <link rel="stylesheet" href="http://openlayers.org/dev/examples/style.css" type="text/css">
    <style>
      .map {
        height: 700px;
        width: 100%;
      }
    </style>
    <script src="http://openlayers.org/dev/OpenLayers.js"></script>
    <script type="text/javascript">

    var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    return;
    }
  }

xmlhttp.open("GET",URL,true);
xmlhttp.setRequestHeader('Authorization','YWRtaW46YWRtaW4=');
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=utf-8");
xmlhttp.send();
var response = xmlhttp.responseText;
        var lon = -77.08391993369312;
        var lat = 38.83950443733243;
        var zoom = 9;
        var map, layer;

        function init(){
            map = new OpenLayers.Map( 'map' );
            layer = new OpenLayers.Layer.WMS( "OpenLayers WMS", 
                    "http://vmap0.tiles.osgeo.org/wms/vmap0",
                    {layers: 'basic'} );
            map.addLayer(layer);
            map.setCenter(new OpenLayers.LonLat(lon, lat), zoom);
            var featurecollection = {
              "type": "FeatureCollection", 
              "features": [
                {
            "type": "Feature",
            "geometry": {

              response.abc.def[0].geometry;
            }
        }
              ]
           };
           var geojson_format = new OpenLayers.Format.GeoJSON();
           var vector_layer = new OpenLayers.Layer.Vector(); 
           map.addLayer(vector_layer);
           vector_layer.addFeatures(geojson_format.read(featurecollection));

        }
    </script>
  </head>
  <body onload="init()">
    <h1 id="title">GeoJSON Example</h1>

    <div id="map" class="map"></div>

  </body>
</html>
Anushree Acharjee
  • 854
  • 5
  • 15
  • 30
  • How far does it get? Do you get the data? Is it generating a new `geojson_format` and `vector_layer`? Is it adding the map? You need can check all these things in the console, but you need to provide more detail. – Andy Jul 09 '14 at 11:36
  • I am hitting a REST API and getting the response shown as JSON Response. Added the entire file. – Anushree Acharjee Jul 09 '14 at 11:42
  • Have you tried this: http://gis.stackexchange.com/questions/23104/openlayers-geojson-files The response is async, so the idea is to send the whole response to a handler, which will then parse the whole JSON and return a feature which you can then add to you vector layer. – John Powell Jul 09 '14 at 14:17

1 Answers1

2

I managed to get your GeoJSON to parse by explicitly stating the type. If you look at the docs you will see that it can take a FeatureCollection (default), a Feature or a Geometry. In your case, you are passing in the geometry, so the type should be geometry.

var geojson_format = new OpenLayers.Format.GeoJSON();
var geometry=geojson_format.read(json.abc.def[0].geometry, "Geometry");
var feature=new OpenLayers.Feature.Vector(geometry);
var vector_layer = new OpenLayers.Layer.Vector(); 
map.addLayer(vector_layer);
vector_layer.addFeatures(feature);

works with your JSON.

John Powell
  • 12,253
  • 6
  • 59
  • 67
  • Thanks John. one small thing.. I am getting the response as var response = "{results: 2938, id: 9283}"; How do i get the elements then? – Anushree Acharjee Jul 10 '14 at 08:36
  • I don't know, where is your geometry? I answered the question based on the JSON sample above, which is different? – John Powell Jul 10 '14 at 08:41
  • yeah, just now observed that the response I get after firing the REST API is enclosed in a double quote. it is actually "{"abc":{"def":[{"ghj":5,"cvb":"m", "geometry":{ "type":"MultiPolygon","coordinates":[[[...]]],"crs":{"type":"name","properties":{"name":"epsg:4326"}} } }]}}" – Anushree Acharjee Jul 10 '14 at 09:07
  • See http://stackoverflow.com/questions/9036429/convert-object-string-to-json. You can use var json = JSON.stringify(eval("(" + str + ")")); to convert your string to json, and then everything should work (assuming you trust the source, as eval has certain risks). – John Powell Jul 10 '14 at 09:14