Reputation: 11
I am new to open layers and currently facing an issue reading and ploting lat and long to center of the map.
I have feature id inside geojson file which is slat
and slong
which I am able to read using var SSlat= feature.get('sat')
and var SSlong =feature.get('slong')
which I am calling inside a style function.
I get lat long for first execution, at the end of complete style function execution var SSlong
and var SSLat
becomes undefined. please let me know is there any way around
var SSlat;
var SSlong;
var styleFunction = function(feature) {
SSlat=feature.get('slat');
SSlong=feature.get('slong');
};
const map = new Map({
layers: [
new TileLayer({
source: new OSM()
}),
new VectorLayer({
source: new VectorSource({
url:'http://127.0.0.1:8080/abc.geojson',
crossOrigin:'null',
projection: 'EPSG:3857',
format: new GeoJSON(),
}),
style: styleFunction
})
],
target: 'map',
view: new View({
center: [-9752120.04, 5132251.45],// here add lat and long which needs to be taken from geojson file
zoom: 13
})
});
Upvotes: 0
Views: 203
Reputation: 17897
I would center the map on the feature's geometry when the feature is loaded. If the slat and slong properties were different and preferred you could use them instead. You should assign your source to a variable to make it easier to reference.
import {getCenter} from 'ol/extent.js';
let vectorSource = new VectorSource({
url:'http://127.0.0.1:8080/abc.geojson',
format: new GeoJSON(),
});
vectorSource.on('addfeature', function(e) {
map.getView().setCenter(getCenter(e.feature.getGeometry().getExtent()));
});
const map = new Map({
layers: [
new TileLayer({
source: new OSM()
}),
new VectorLayer({
source: vectorSource,
style: styleFunction
})
],
target: 'map',
view: new View({
center: [-9752120.04, 5132251.45],// here add lat and long which needs to be taken from geojson file
zoom: 13
})
});
To center using slat
and slong
properties from features
vectorSource.on('addfeature', function(e) {
var SSlat = e.feature.get('slat');
var SSlong = e.feature.get('slong');
if (SSlat && SSlong) {
map.getView().setCenter(fromLonLat([SSlong, SSlat]);
}
});
you may need to use [Number(SSlong), Number(SSlat)]
if the property is a string
Upvotes: 1