Как добавить пользовательский маркер на карту mapbox, которая отображает всплывающие окна при наведении?

#mapbox

#mapbox

Вопрос:

Заранее прошу прощения, если мой вопрос звучит глупо, но я здесь над головой …

Я пытаюсь создать карту с помощью mapbox с пользовательскими маркерами, которые отображают всплывающее окно при наведении. Я последовал этому руководству, скопировал код и добавил свои места и описания, но я не могу изменить URL пользовательского маркера. Есть ли способ изменить код, чтобы я мог сохранить эффект наведения, но с моими пользовательскими маркерами?

Большое вам спасибо!

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Display a popup on hover</title>
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />
<script src="https://api.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.js"></script>
<link href="https://api.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.css" rel="stylesheet" />
<style>
    body { margin: 0; padding: 0; }
    #map { position: absolute; top: 0; bottom: 0; width: 100%; }
</style>
</head>
<body>
<style>
.mapboxgl-popup {
max-width: 400px;
font: 12px/20px 'Helvetica Neue', Arial, Helvetica, sans-serif;
}
</style>
<div id="map"></div>
<script>
    mapboxgl.accessToken = 'pk.eyJ1IjoicGllcm8xMDEiLCJhIjoiY2toNHY1ejFqMGV5ajJyczVxeHAwcHo3eCJ9.xauie-TVwLVSYj3l6AAmOw';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v11',
center: [-77.04, 38.907],
zoom: 11.15
});
 
map.on('load', function () {
map.loadImage(
'https://docs.mapbox.com/mapbox-gl-js/assets/custom_marker.png',
// Add an image to use as a custom marker
function (error, image) {
if (error) throw error;
map.addImage('custom-marker', image);
 
map.addSource('places', {
'type': 'geojson',
'data': {
'type': 'FeatureCollection',
'features': [
{
'type': 'Feature',
'properties': {
'description':
'<strong>Make it Mount Pleasant</strong><p>Make it Mount Pleasant is a handmade and vintage market and afternoon of live entertainment and kids activities. 12:00-6:00 p.m.</p>'
},
'geometry': {
'type': 'Point',
'coordinates': [-77.038659, 38.931567]
}
},
]
}
});
 
// Add a layer showing the places.
map.addLayer({
'id': 'places',
'type': 'symbol',
'source': 'places',
'layout': {
'icon-image': 'custom-marker',
'icon-allow-overlap': true
}
});
}
);
 
// Create a popup, but don't add it to the map yet.
var popup = new mapboxgl.Popup({
closeButton: false,
closeOnClick: false
});
 
map.on('mouseenter', 'places', function (e) {
// Change the cursor style as a UI indicator.
map.getCanvas().style.cursor = 'pointer';
 
var coordinates = e.features[0].geometry.coordinates.slice();
var description = e.features[0].properties.description;
 
// Ensure that if the map is zoomed out such that multiple
// copies of the feature are visible, the popup appears
// over the copy being pointed to.
while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {
coordinates[0]  = e.lngLat.lng > coordinates[0] ? 360 : -360;
}
 
// Populate the popup and set its coordinates
// based on the feature found.
popup.setLngLat(coordinates).setHTML(description).addTo(map);
});
 
map.on('mouseleave', 'places', function () {
map.getCanvas().style.cursor = '';
popup.remove();
});
});
</script>
 
</body>
</html>
 

Ответ №1:

  1. Ваш код работает отлично, включая всплывающее окно при наведении. Чтобы изменить изображение маркера, замените используемый здесь URL…
 map.loadImage(
'https://docs.mapbox.com/mapbox-gl-js/assets/custom_marker.png'
 

…на другой URL-адрес, например:

 map.loadImage(
'https://i.imgur.com/kiw0dR2.png'
 

Вот скриншот вашего кода и карты до и после изменения URL.

  1. Пожалуйста, обратите внимание, что ваш токен pk.ey... должен быть приватным, а не общедоступным на общедоступных форумах. Чтобы защитить этот токен от несанкционированного использования, вы можете повернуть этот токен, применяя ограничения URL, чтобы он работал только на таких сайтах, как CodePen или JSFiddle.