I get the data from MSsql server 2012 in json format, i get just WKT string to convert for showing on the map using ol.format.WKT() .
I want to show the ID and the name of the polygon when i click, on popup. How can i recognize in which polygon am i clicking?
How can i know the map in which polygon I click and get me the data of that polygon?
for (var i = 0; i < geometries.length; i++) {
var feature = wktReader.readFeature(geometries[i].GeomCol1.Geometry.WellKnownText);
feature.getGeometry().transform('EPSG:4326', 'EPSG:3857');
if (feature.getGeometry().getType() == 'Polygon') {
feature.setStyle(new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'blue',
width: 1
}),
fill: new ol.style.Fill({
color: 'rgba(0, 0, 255, 0.1)'
})
}));
featureCollection.push(feature);
}
}
this is a part how i get just wkt string.
These are the polygons that i have shown, and i want to show a popup with the informations of the polygon which i click
This is a picture of how i have stored the spatial data in my MSsql server
Thanks
forEachFeatureAtPixel
(api doc) can get you all the features on a certain position. Admittedly, it can be confusing to use. The callback you pass to that function is called for every layer. If the callback returns a truthy value, it stops and then forEachFeatureAtPixel returns whatever your callback returned. This makes it perfect to select a specific feature.
var count = 2000;
var features = new Array(count);
var e = 4500000;
for (var i = 0; i < count; ++i) {
var coordinates = [2 * e * Math.random() - e, 2 * e * Math.random() - e];
features[i] = new ol.Feature({
geometry: new ol.geom.Point(coordinates),
myHappyAttribute: ('you are beautiful ' + i)
});
}
var source = new ol.source.Vector({
features: features
});
var layer = new ol.layer.Vector({source: source});
const view = new ol.View({
center: [2500000, 0], zoom: 5
});
const map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
}),
layer
],
target: 'map',
view
});
map.on('singleclick', function(evt) {
const pixel = map.getEventPixel(evt.originalEvent);
const feature = map.forEachFeatureAtPixel(
pixel,
someFeature => someFeature, // return first element
{
hitTolerance: 2 // how far off the click can be
}
);
if (feature) {
const attr = feature.get('myHappyAttribute');
console.log('clicked on feature with attr:', attr);
} else {
console.log('not clicked on a feature');
}
});
<link href="https://openlayers.org/en/v4.6.5/css/ol.css" rel="stylesheet"/>
<script src="https://openlayers.org/en/v4.6.5/build/ol-debug.js"></script>
<div id="map" class="map"></div>