0
votes

I've created a custom map and style in Mapbox and I'm trying to further customize the map with popups and highlights.

I'm new to coding and I'm having trouble making a popup event occur when hovering mouse over polygon. I've been successful at creating the popup with a point/marker, but I would like the shapefiles to highlight upon hover and with a click event, show a popup with more custom information (unrelated to the attribute table in the original shape file).

Is there a simple script for this? I'm wondering if my shapefile to geojson conversion is bad?

1

1 Answers

0
votes

You should check out this example which demonstrates how to accomplish this using mapbox-gl-js. Heres the code:

<!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.17.0/mapbox-gl.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.17.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;
}

.marker-title {
    font-weight: 700;
}
</style>
<div id='map'></div>
<script>
mapboxgl.accessToken = '<your access token here>';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v8',
center: [-100.04, 38.907],
zoom: 3
});

map.on('load', function () {
    // Add marker data as a new GeoJSON source.
    map.addSource('states', {
        'type': 'geojson',
        'data': 'https://d2ad6b4ur7yvpq.cloudfront.net/naturalearth-3.3.0/ne_110m_admin_1_states_provinces_shp.geojson'
    });

    // Add a layer showing the markers.
    map.addLayer({
        'id': 'states-layer',
        'type': 'fill',
        'source': 'states',
        'paint': {
            'fill-color': 'rgba(200, 100, 240, 0.4)',
            'fill-outline-color': 'rgba(200, 100, 240, 1)'
        }
    });
});


// When a click event occurs near a marker icon, open a popup at the location of
// the feature, with description HTML from its properties.
map.on('click', function (e) {
    var features = map.queryRenderedFeatures(e.point, { layers: ['states-layer'] });
    if (!features.length) {
        return;
    }

    var feature = features[0];

    var popup = new mapboxgl.Popup()
        .setLngLat(map.unproject(e.point))
        .setHTML(feature.properties.name)
        .addTo(map);
});

// Use the same approach as above to indicate that the symbols are clickable
// by changing the cursor style to 'pointer'.
map.on('mousemove', function (e) {
    var features = map.queryRenderedFeatures(e.point, { layers: ['states-layer'] });
    map.getCanvas().style.cursor = (features.length) ? 'pointer' : '';
});
</script>

</body>
</html>

Hope this helps out!