将singleclick事件绑定到地图
map.on('singleclick', event => {
// get the feature you clicked
const feature = map.forEachFeatureAtPixel(event.pixel, (feature) => {
return feature
})
if(feature instanceof ol.Feature){
// Fit the feature geometry or extent based on the given map
map.getView().fit(feature.getGeometry())
// map.getView().fit(feature.getGeometry().getExtent())
}
})
为您提供单独的 HTML 文件!
<!DOCTYPE html>
<html>
<head>
<title>GeoJSON</title>
<link
rel="stylesheet"
href="https://openlayers.org/en/v4.6.5/css/ol.css"
type="text/css"
/>
<!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
<script src="https://openlayers.org/en/v4.6.5/build/ol.js"></script>
</head>
<body>
<div id="map" class="map"></div>
<script>
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,
}),
};
var styleFunction = function (feature) {
return styles[feature.getGeometry().getType()];
};
var geojsonObject = {
type: "FeatureCollection",
crs: {
type: "name",
properties: {
name: "EPSG:3857",
},
},
features: [
{
type: "Feature",
geometry: {
type: "Point",
coordinates: [0, 0],
},
},
{
type: "Feature",
geometry: {
type: "Point",
coordinates: [13369643, 3572500],
},
},
],
};
var vectorSource = new ol.source.Vector({
features: new ol.format.GeoJSON().readFeatures(geojsonObject),
});
var vectorLayer = new ol.layer.Vector({
source: vectorSource,
style: styleFunction,
});
var map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.OSM(),
}),
vectorLayer,
],
target: "map",
controls: ol.control.defaults({
attributionOptions: {
collapsible: false,
},
}),
view: new ol.View({
center: [0, 0],
zoom: 2,
}),
});
map.on("singleclick", (event) => {
// get the feature you clicked
const feature = map.forEachFeatureAtPixel(event.pixel, (feature) => {
return feature;
});
if (feature instanceof ol.Feature) {
// Fit the feature geometry or extent based on the given map
map.getView().fit(feature.getGeometry());
// map.getView().fit(feature.getGeometry().getExtent())
}
});
</script>
</body>
</html>