OpenLayers - GeoJSON

by Jonatas Walker

HTML

<script src="//openlayers.org/en/v3.16.0/build/ol.js"></script>
<link rel="stylesheet" href="//openlayers.org/en/v3.16.0/css/ol.css">
<div class="input">
  <input type="text" id="id-input" placeholder="Click on a marker ...">
</div>
<div id="map" class="map"></div>

CSS

html, body, #map {
  height: 100%;
  overflow: hidden;
}
.input {
  margin: 5px;
}
#id-input{ width: 300px }

JavaScript

var vectorLayer = new ol.layer.Vector({
  source: new ol.source.Vector({
    format: new ol.format.GeoJSON(),
    url: 'https://cdn.rawgit.com/openlayers/openlayers/master/examples/data/geojson/point-samples.geojson'
  }),
  style: new ol.style.Style({
    image: new ol.style.Circle({
      radius: 10,
      fill: new ol.style.Fill({
        color: 'green'
      })
    })
  })
});
var rasterLayer = new ol.layer.Tile({
  source: new ol.source.TileJSON({
    url: 'https://api.tiles.mapbox.com/v3/mapbox.geography-class.json',
    crossOrigin: ''
  })
});
var map = new ol.Map({
  layers: [rasterLayer, vectorLayer],
  target: document.getElementById('map'),
  view: new ol.View({
    center: ol.proj.fromLonLat([-75.289080414181669, 48.284706278302295]),
    zoom: 6
  })
});

var input = document.getElementById('id-input');

var select_interaction = new ol.interaction.Select();
map.addInteraction(select_interaction);

select_interaction.on('select', function(evt) {
  var features = select_interaction.getFeatures();
  var value = '';
  features.forEach(function(feature){
    // change this to your own needs
    value += feature.get('name') + ', ';
  });
  
  input.value = value;
});

map.on('pointermove', function(e) {
  if (e.dragging) return;
  var hit = map.hasFeatureAtPixel(map.getEventPixel(e.originalEvent));
  map.getTarget().style.cursor = hit ? 'pointer' : '';
});