Skip to content

Instantly share code, notes, and snippets.

@bellbind
Created January 15, 2020 07:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bellbind/87973c2630939130e234916de88674ed to your computer and use it in GitHub Desktop.
Save bellbind/87973c2630939130e234916de88674ed to your computer and use it in GitHub Desktop.
[broeswe][openlayers] Example for OpenLayers (with OpenStreetMap tiles)
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.1.1/css/ol.css" type="text/css">
<style>
.map {
height: 90vh;
width: 90vw;
}
</style>
<script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.1.1/build/ol.js"></script>
<script type="module">
const startPoint = ol.proj.fromLonLat([139.7, 35.7]);
// black circle marker
window.marker = new ol.Feature({
geometry: new ol.geom.Point(startPoint),
});
const fill = new ol.style.Fill({color: "rgb(0,0,0)"});
const style = new ol.style.Style({
image: new ol.style.Circle({fill, radius: 5}),
});
marker.setStyle(style);
// map
window.map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM(),
}),
new ol.layer.Vector({
source: new ol.source.Vector({features: [marker]}),
}),
],
view: new ol.View({
center: startPoint,
zoom: 18,
})
});
//event handlers
map.addEventListener("moveend", ev => {
const center = map.getView().getCenter();
const lonlat = ol.proj.toLonLat(center);
document.getElementById("center").textContent = lonlat.join(", ");
document.getElementById("osm").href =
`https://www.openstreetmap.org/?zoom=${map.getView().getZoom()}&mlon=${lonlat[0]}&mlat=${lonlat[1]}`;
marker.setGeometry(new ol.geom.Point(center));
});
map.addEventListener("click", ev => {
//console.log(ev.coordinate);
map.getView().setCenter(ev.coordinate);
marker.setGeometry(new ol.geom.Point(ev.coordinate));
});
</script>
<title>OpenLayers</title>
</head>
<body>
<h2>
Center (Lon Lat): <span id="center">139.7, 35.7</span>
<a href="https://www.openstreetmap.org/?zoom=18&mlon=139.7&mlat=35.7"
id="osm" target="_blank">Open with OSM</a>
</h2>
<div id="map" class="map"></div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment