Created
May 23, 2016 18:16
-
-
Save tristen/10b69f89b600ca0433fdc472db6a6cab to your computer and use it in GitHub Desktop.
Mapbox GL JS map with custom DOM marker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset='utf-8' /> | |
<title></title> | |
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' /> | |
<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.18.0/mapbox-gl.js'></script> | |
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.18.0/mapbox-gl.css' rel='stylesheet' /> | |
<style> | |
body { margin:0; padding:0; } | |
.map { position:absolute; top:0; bottom:0; width:100%; } | |
.custom-marker { | |
position:absolute; | |
z-index:1; | |
display:block; | |
border-radius:50%; | |
background-color:#f86767; | |
-webkit-box-shadow:inset 0 0 0 4px rgba(255,255,255,0.25); | |
box-shadow:inset 0 0 0 4px rgba(255,255,255,0.25); | |
} | |
</style> | |
</head> | |
<body> | |
<div id='map' class='map'></div> | |
<script> | |
// Coordinates we'll use to center the map and position the custom marker. | |
var coordinates = [-74.5, 40] | |
mapboxgl.accessToken = 'pk.eyJ1IjoidHJpc3RlbiIsImEiOiJiUzBYOEJzIn0.VyXs9qNWgTfABLzSI3YcrQ'; | |
var map = new mapboxgl.Map({ | |
container: 'map', | |
style: 'mapbox://styles/mapbox/streets-v8', | |
center: coordinates, | |
zoom: 9 | |
}); | |
map.on('load', function() { | |
// Return the x/y position from coordinates | |
var width = height = 40; | |
var position = map.project(coordinates); | |
// Create a custom marker and add it to the map | |
var marker = document.createElement('div'); | |
marker.className = 'custom-marker'; | |
marker.style.width = width + 'px'; | |
marker.style.height = height + 'px'; | |
// Set the top + left position of the marker | |
// Based on the coordinates and half the size of its shape | |
marker.style.top = position.y - height / 2 + 'px'; | |
marker.style.left = position.x - width / 2 + 'px'; | |
// Append the marker to the map. | |
map.getContainer().appendChild(marker); | |
map.on('move', function() { | |
// Update the x/y coordinates based on the new position of the map. | |
position = map.project(coordinates); | |
marker.style.top = position.y - height / 2 + 'px'; | |
marker.style.left = position.x - width / 2 + 'px'; | |
}); | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Wow this was what I was looking for! Thank you!