Created
December 6, 2018 10:09
-
-
Save glafarge/5b6deca504c6d248683c0a36fdcec506 to your computer and use it in GitHub Desktop.
Mapbox markers hover + click
This file contains hidden or 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
const map = new mapboxgl.Map({ | |
container: 'map', | |
style: 'mapbox://styles/****/********', | |
center: [-0.579180, 44.837788], | |
zoom: 12.0 | |
}); | |
map.on('load', function() { | |
// ==================================== | |
// Points | |
// ==================================== | |
var points = [{ | |
latlng: [-0.579180, 44.837788], | |
url: 'http://disney.fr', | |
title: 'Point n°1', | |
color:'#e16715' | |
},{ | |
latlng: [-0.572907,44.839055], | |
url: 'http://google.fr', | |
title: 'Point n°2', | |
color:'#ff2700' | |
}]; | |
// ==================================== | |
// Popup configuration | |
// ==================================== | |
var markerHeight = 40, | |
markerRadius = 10, | |
linearOffset = 8; | |
var popupOffsets = { | |
'top': [0, 0], | |
'top-left': [0,0], | |
'top-right': [0,0], | |
'bottom': [0, -markerHeight], | |
'bottom-left': [linearOffset, (markerHeight - markerRadius + linearOffset) * -1], | |
'bottom-right': [-linearOffset, (markerHeight - markerRadius + linearOffset) * -1], | |
'left': [markerRadius, (markerHeight - markerRadius) * -1], | |
'right': [-markerRadius, (markerHeight - markerRadius) * -1] | |
}; | |
// ==================================== | |
// Add markers and popups | |
// ==================================== | |
var markers = []; | |
var marker, popup; | |
points.forEach(function(point) { | |
marker = new mapboxgl.Marker({color:point.color}) | |
.setLngLat(point.latlng) | |
.addTo(map); | |
marker._element.style.cursor = 'pointer'; | |
marker.props = point; | |
popup = new mapboxgl.Popup({closeButton:false, offset:popupOffsets}) | |
.setLngLat(point.latlng) | |
.setHTML(point.title); | |
marker.props.popup = popup; // save it to marker props | |
markers.push(marker); | |
}); | |
map.on('click', function(e) { | |
const targetElement = e.originalEvent.target; | |
markers.forEach(function(marker) { | |
const element = marker._element; | |
if (targetElement === element || element.contains(targetElement)) { | |
window.open(marker.props.url, '_blank'); | |
} | |
}); | |
}); | |
map.on('mousemove', function(e) { | |
const targetElement = e.originalEvent.target; | |
const element = marker._element; | |
markers.forEach(function(marker) { | |
const element = marker._element; | |
if (targetElement === element || element.contains(targetElement)) { | |
marker.props.popup.addTo(map); | |
} | |
else { | |
marker.props.popup.remove(); | |
} | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment