Skip to content

Instantly share code, notes, and snippets.

@anthonyeden
Last active September 25, 2022 20:17
Show Gist options
  • Save anthonyeden/69c6eee056d61fcaaad9159058952309 to your computer and use it in GitHub Desktop.
Save anthonyeden/69c6eee056d61fcaaad9159058952309 to your computer and use it in GitHub Desktop.
OpenStreetMap & OpenLayers: Creating A Map With Markers
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>OpenStreetMap &amp; OpenLayers - Marker Example</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="https://openlayers.org/en/v4.6.5/css/ol.css" type="text/css">
<script src="https://openlayers.org/en/v4.6.5/build/ol.js" type="text/javascript"></script>
<script>
/* OSM & OL example code provided by https://mediarealm.com.au/ */
var map;
var mapLat = -33.829357;
var mapLng = 150.961761;
var mapDefaultZoom = 10;
function initialize_map() {
map = new ol.Map({
target: "map",
layers: [
new ol.layer.Tile({
source: new ol.source.OSM({
url: "https://a.tile.openstreetmap.org/{z}/{x}/{y}.png"
})
})
],
view: new ol.View({
center: ol.proj.fromLonLat([mapLng, mapLat]),
zoom: mapDefaultZoom
})
});
}
function add_map_point(lat, lng) {
var vectorLayer = new ol.layer.Vector({
source:new ol.source.Vector({
features: [new ol.Feature({
geometry: new ol.geom.Point(ol.proj.transform([parseFloat(lng), parseFloat(lat)], 'EPSG:4326', 'EPSG:3857')),
})]
}),
style: new ol.style.Style({
image: new ol.style.Icon({
anchor: [0.5, 0.5],
anchorXUnits: "fraction",
anchorYUnits: "fraction",
src: "https://upload.wikimedia.org/wikipedia/commons/e/ec/RedDot.svg"
})
})
});
map.addLayer(vectorLayer);
}
</script>
</head>
<body onload="initialize_map(); add_map_point(-33.8688, 151.2093);">
<div id="map" style="width: 100vw; height: 100vh;"></div>
</body>
</html>
<?php
// Example script to proxy OSM Tiles
// Written by Anthony Eden (https://mediarealm.com.au)
// This is a simplistic example without any caching
// For an example with caching, see https://wiki.openstreetmap.org/wiki/ProxySimplePHP
$x = $_GET['x'];
$y = $_GET['y'];
$z = $_GET['z'];
if(!is_numeric($x) || !is_numeric($y) || !is_numeric($z)) {
http_response_code(404);
die("404 Not Found");
}
$ch = curl_init('https://maps.wikimedia.org/osm-intl/'.$z.'/'.$x.'/'.$y.'.png');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$image = curl_exec($ch);
if(curl_getinfo($ch, CURLINFO_RESPONSE_CODE) == "404") {
http_response_code(404);
curl_close($ch);
die("404 Not Found");
}
header ('Content-Type: image/png');
header("Access-Control-Allow-Origin: *");
echo $image;
curl_close($ch);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment