Как установить несколько маркеров на одинаковые координаты с mapbox? - PullRequest
0 голосов
/ 21 февраля 2020

Я использую mapbox GL для упомянутой компании по производству видеоигр, базирующейся в Африке. Все эти компании размещены на карте: https://africangamingnetworks.com/

Когда у меня есть несколько маркеров с одинаковыми координатами, например, две компании в Яунде, Камерун, mapbox показывает только первую, потому что они имеют одинаковую широту и долготу.

Как мне сделать так, чтобы все маркеры были с одинаковыми координатами?

Заранее спасибо.

<%@ include file="/init.jsp"%>
<div class="shadow row">
    <div class=" col-12 rounded-sm " id='map'
        style='height: 800px;'></div>

</div>


<script>
    mapboxgl.accessToken = 'pk.eyJ1Ijoia29zdGVkIiMWQzbXA3M2ZxYmd5MnkifQ.faOl-gGzibR9yMpZ-i7FTQ';
    var map = new mapboxgl.Map({
        container : 'map',
        style : 'mapbox://styles/mapbox/streets-v11',
        zoom : 2
    // starting zoom
    });

    // Add zoom and rotation controls to the map.
    map.addControl(new mapboxgl.NavigationControl());

    var studioListComplete = [];

    <c:forEach var="studio" items="${studioList}">

    studioListComplete
            .push({
                "type" : "Feature",
                "properties" : {
                    "description" : "<strong>${studio.studioName} (${studio.country})</strong> <br/><br/>" + 
                                    "${studio.studioDescription}<br/><br/>"+
                                    "<strong>City : </strong>${studio.city}<br/>"+
                                    "<strong>Number of employees : </strong>${studio.numberOfEmployees}<br/>"+
                                    "<strong>Phone : </strong>${studio.phoneNumber}<br/><br/>"+

                                    "<a href=\"${studio.webSiteUrl}\" target=\"_blank\">Please visit our website</a>",
                    "icon": "rocket"
                },
                "geometry" : {
                    "type" : "Point",
                    "coordinates" : [ "${studio.longitude}",
                            "${studio.latitude}" ]
                }
            });
    //var marker = new mapboxgl.Marker()
    //.setLngLat(["${studio.longitude}", "${studio.latitude}"])
    //.addTo(map);
    </c:forEach>

    console.log(studioListComplete);

    map.on('load', function() {
        // Add a layer showing the places.
        map.addLayer({
            "id" : "places",
            "type" : "symbol",
            "source" : {
                "type" : "geojson",
                "data" : {
                    "type" : "FeatureCollection",
                    "features" : studioListComplete
                }
            },
            "layout" : {
                "icon-image" : "{icon}-15",
                'icon-size': 1,
                "icon-allow-overlap" : true
            }
        });

        // When a click event occurs on a feature in the places layer, open a popup at the
        // location of the feature, with description HTML from its properties.
        map.on('click', 'places', function(e) {
            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;
            }

            new mapboxgl.Popup().setLngLat(coordinates).setHTML(description)
                    .addTo(map);
        });

        // Change the cursor to a pointer when the mouse is over the places layer.
        map.on('mouseenter', 'places', function() {
            map.getCanvas().style.cursor = 'pointer';
        });

        // Change it back to a pointer when it leaves.
        map.on('mouseleave', 'places', function() {
            map.getCanvas().style.cursor = '';
        });
    });
</script>

<style>
    //Style is here

</style>

1 Ответ

0 голосов
/ 28 февраля 2020

Если вы хотите, чтобы два дискретных маркера отображались для точек с одинаковыми координатами, лучше всего слегка изменить широту и долготу одной из точек, чтобы она не находилась непосредственно над другой. .

В качестве альтернативы, если нет возможности изменить данные координат, вы можете исследовать кластеризацию своих данных, чтобы было наглядно видеть, что несколько компаний находятся в одном кластере. В этом примере показано, как создавать и стилизовать кластеры с использованием слоя круга по умолчанию, а в в этом примере показано, как можно настраивать визуальные кластеры.

...