14 votos

Añadir capa GeoJSON a OpenLayers 3

Tengo un archivo GeoJSON llamado mygeojson.json y quiero añadirlo como capa en OpenLayers 3 encima de una capa de openstreetmap. Hasta ahora he podido mostrar el mundo de openstreetmap, incluyendo el zoom, etc., pero por alguna razón no puedo poner el mygeojson.json en él.

El geojson contiene muchos polígonos y tiene el siguiente aspecto:

{
"type": "FeatureCollection",
"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },

"features": [
      { "type": "Feature", "properties": { "DN": 2 }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 13.559093915055664, 52.545214330050563 ], [ 13.559633429050496, 52.545205649772548 ], [ 13.559633415380715, 52.545214636296755 ], [ 13.559093915055664, 52.545214330050563 ] ] ] } }
]
}

mi main.html:

<!doctype html>
<html lang="en">
  <head>
    <link rel='stylesheet' href='http://ol3js.org/en/master/css/ol.css'>
    <style>
      #map {
        height: 100%;
        width: 100%;
      }
    </style>
    <title>OpenLayers 3 example</title>
    <script src="ol3/ol.js" type="text/javascript"></script>
  </head>
  <body>
    <h1>My Map</h1>
    <div id="map"></div>
    <script type="text/javascript">
      var map = new ol.Map({
        target: 'map',
        layers: [
           new ol.layer.Tile({
              source: new ol.source.OSM()
           }),
           new ol.layer.Vector({
              title: 'added Layer',
              source: new ol.source.GeoJSON({
                 projection : 'EPSG:4326',
                 url: 'mygeojson.json'
              })
           })
        ],
        view: new ol.View({
          center:[52.5243700 , 13.4105300],
          zoom:2

        })
      });
    </script>
  </body>
</html>

También he probado a quitar la información de la proyección pero no sirve de nada.

20voto

user51613 Puntos 91

Para tu información... creo que esto ha cambiado para OL3 V3.5.0, así que la respuesta de gcarrillo sería:

new ol.layer.Vector({
      title: 'added Layer',
      source: new ol.source.Vector({
         url: 'mygeojson.json',
         format: new ol.format.GeoJSON()
      })
  })

Puede ver los cambios aquí: https://github.com/openlayers/ol3/blob/master/changelog/upgrade-notes.md#v350

10voto

Elliott Maynard Puntos 11

Cuando defina su fuente vectorial, ponga la configuración de la proyección apuntando al sistema de referencia de coordenadas objetivo (véase los documentos ):

new ol.layer.Vector({
      title: 'added Layer',
      source: new ol.source.GeoJSON({
         projection : 'EPSG:3857',
         url: 'mygeojson.json'
      })
  })

Mira este ejemplo (usando tus datos de muestra): http://jsfiddle.net/zzahmbff/4/

Tal vez este recurso pueda ayudarle a ver diferentes formas de cargar datos vectoriales: http://acanimal.github.io/thebookofopenlayers3/chapter03_03_vector_source.html

8voto

todd kman Puntos 11

La API de vectores de OpenLayers está cambiando mucho. Tengo una muestra de trabajo con OpenLayers 3.16.0.

Es importante que defina featureProjection: 'EPSG:3857' en las opciones de readFeatures así:

.readFeatures(_geojson_object, { featureProjection: 'EPSG:3857' })

La referencia puede encontrarse en https://github.com/openlayers/ol3/blob/master/changelog/upgrade-notes.md#v350

Ejemplo:

_geojson_vectorSource = new ol.source.Vector({
  features: (new ol.format.GeoJSON()).readFeatures(_geojson_object, { featureProjection: 'EPSG:3857' })
});

_geojson_vectorLayer = new ol.layer.Vector({
  source: _geojson_vectorSource,
  style: styleFunction
});

map.addLayer(_geojson_vectorLayer);

Nota: styleFunction

var image = new ol.style.Circle({
  radius: 5,
  fill: null,
  stroke: new ol.style.Stroke({ color: 'red', width: 1 })
});

var styles = {
  'Point': new ol.style.Style({
    image: image
  }),
  'LineString': new ol.style.Style({
    stroke: new ol.style.Stroke({
      color: 'green',
      width: 1
    })
  }),
  'MultiLineString': new ol.style.Style({
    stroke: new ol.style.Stroke({
      color: 'green',
      width: 1
    })
  }),
  'MultiPoint': new ol.style.Style({
    image: image
  }),
  'MultiPolygon': new ol.style.Style({
    stroke: new ol.style.Stroke({
      color: 'yellow',
      width: 1
    }),
    fill: new ol.style.Fill({
      color: 'rgba(255, 255, 0, 0.1)'
    })
  }),
  'Polygon': new ol.style.Style({
    stroke: new ol.style.Stroke({
      color: 'blue',
      lineDash: [4],
      width: 3
    }),
    fill: new ol.style.Fill({
      color: 'rgba(0, 0, 255, 0.1)'
    })
  }),
  'GeometryCollection': new ol.style.Style({
    stroke: new ol.style.Stroke({
      color: 'magenta',
      width: 2
    }),
    fill: new ol.style.Fill({
      color: 'magenta'
    }),
    image: new ol.style.Circle({
      radius: 10,
      fill: null,
      stroke: new ol.style.Stroke({
        color: 'magenta'
      })
    })
  }),
  'Circle': new ol.style.Style({
    stroke: new ol.style.Stroke({
      color: 'red',
      width: 2
    }),
    fill: new ol.style.Fill({
      color: 'rgba(255,0,0,0.2)'
    })
  })
};

var styleFunction = function (feature) {
  return styles[feature.getGeometry().getType()];
};

i-Ciencias.com

I-Ciencias es una comunidad de estudiantes y amantes de la ciencia en la que puedes resolver tus problemas y dudas.
Puedes consultar las preguntas de otros usuarios, hacer tus propias preguntas o resolver las de los demás.

Powered by:

X