Рисование многоугольника на листовке с местонахождением пользователя - PullRequest
0 голосов
/ 08 мая 2020

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

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

Может ли кто-нибудь посоветовать мне, как я могу добавить многоугольник в форме шестиугольника в местоположение пользователя.

В настоящее время я получаю местоположение пользователя с помощью API геолокации, но я также немного озадачен, чтобы нарисовать шестиугольник. Ниже у меня есть код местоположения, который ставит маркер на местоположение пользователя и многоугольник basi c stati c (многоугольник - это не более чем заполнитель). Я попытался воспроизвести код навигатора, чтобы добавить многоугольник в местоположении пользователя, но он продолжает ломать карту, и я немного не понимаю, как это сделать.

Любая помощь будет принята с благодарностью.

    navigator.geolocation.getCurrentPosition(function (position) {
        var userMarker = L.marker([position.coords.latitude, position.coords.longitude]).addTo(mymap);
    })

    var userPolygon = [{
        "type": "Feature",
        "properties": {},
        "geometry": {
            "type": "Polygon",
            "coordinates": [
                [
                    [-1.5268367528915405,54.98091997292441],
                    [-1.5270352363586424,54.98074450562538],
                    [-1.5267670154571533,54.98054748879672],
                    [-1.5262091159820557,54.980541332005245],
                    [-1.5259945392608643,54.98072911372045],
                    [-1.5262305736541748,54.98091689455734],
                    [-1.5268367528915405,54.98091997292441]
                ]
            ]
        }
    }].addTo(mymap);

Спасибо @FalkeDesign за вашу помощь. Я добавил обновленный код ниже и был бы очень признателен, если бы вы могли указать, почему они не отображаются

<script>


    var mymap = L.map('mapid').setView([57.149860, -2.102930], 13);
    L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
        attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
    }).addTo(mymap);

    // //var to capture user position and place marker 
    // navigator.geolocation.getCurrentPosition(function (position) {
    //  var userMarker = L.marker([position.coords.latitude, position.coords.longitude]).addTo(mymap);
    // })

    var fog = L.rectangle([[54.98652836571122, -1.542469837492442], [54.973032422136875, -1.4963848081781708]]);
    var fogLayer = L.geoJSON(fog.toGeoJSON()).addTo(myMap);

    function subtract() {
        var radius = 0.01;
        var hex = createHex(myMap.getCenter(), radius); //replace center with navigator point
        var templayer = L.geoJSON(turf.difference(fogLayer.getLayers()[0].toGeoJSON(), hex.toGeoJSON()));
        fogLayer.removeFrom(myMap);
        fogLayer = templayer.addTo(myMap)
    }


    function createHex(center, radius) {
        var centerp = turf.point([center.lng, center.lat]);
        var points = [];
        points.push(turf.destination(centerp, radius, 90));
        points.push(turf.destination(centerp, radius, 150));
        points.push(turf.destination(centerp, radius, -150));
        points.push(turf.destination(centerp, radius, -90));
        points.push(turf.destination(centerp, radius, -30));
        points.push(turf.destination(centerp, radius, 30));

        var hex = L.polygon([]);
        points.forEach((p) => {
            hex.addLatLng([p.geometry.coordinates[1], p.geometry.coordinates[0]]);
        });
        return hex;
    }

    subtract();
    myMap.on('move', subtract);







    ////Add custom user icon
    // var userIcon = L.icon({
    //  iconUrl: 'prototype\img\icons8-user-location-48.png',

    //  iconSize: [48, 48], // size of the icon
    //  shadowSize:   [0, 0], // size of the shadow
    //  iconAnchor: [22, 94], // point of the icon which will correspond to marker's location

    // });




    //Fog polygon
    var fogPolygon =
    {
        "type": "FeatureCollection",
        "features": [
            {
                "type": "Feature",
                "properties": {},
                "geometry": {
                    "type": "Polygon",
                    "coordinates": [
                        [
                            [
                                -175.078125,
                                84.9901001802348
                            ],
                            [
                                -174.375,
                                -85.05112877980659
                            ],
                            [
                                197.578125,
                                -84.92832092949963
                            ],
                            [
                                197.578125,
                                84.9901001802348
                            ],
                            [
                                -175.078125,
                                84.9901001802348
                            ]
                        ]
                    ]
                }
            }
        ]
    };

    L.geoJSON(fogPolygon, {
        style: function (feature) {
            return {
                color: '#000000',
                weight: 0.2,
            }
        }
    }).addTo(mymap);








    /*PoI Placeholders*/
    var duthiePark = L.polygon([
        [57.12896, -2.107036],
        [57.12882, -2.101028],
        [57.130765, -2.097294],
        [57.132512, -2.102809],
        [57.131906, -2.107852],
        [57.130776, -2.106779]
    ]).addTo(mymap);

    var robertGordon = L.polygon([
        [57.119828, -2.150552],
        [57.117568, -2.148342],
        [57.117661, -2.136669],
        [57.118232, -2.129974],
        [57.11963, -2.130404],
        [57.119886, -2.136497],
        [57.118768, -2.14493]
    ]).addTo(mymap);

    var pittodrie = L.polygon([
        [57.159646, -2.090192],
        [57.158436, -2.090299],
        [57.158587, -2.086523],
        [57.159693, -2.086844],
    ]).addTo(mymap);

    var unionTerraceGardens = L.polygon([
        [57.14575, -2.101521],
        [57.147612, -2.103775],
        [57.147612, -2.104461],
        [57.147147, -2.104826],
        [57.145598, -2.102122]
    ]).addTo(mymap);

    var unionSquare = L.polygon([
        [57.144166, -2.098882],
        [57.145098, -2.095771],
        [57.142653, -2.092767],
        [57.141582, -2.095771]
    ]).addTo(mymap);

    var marischalCollege = L.polygon([
        [57.150301, -2.096007],
        [57.149475, -2.097552],
        [57.14838, -2.096329],
        [57.149044, -2.095428],
        [57.14951, -2.095084],
        [57.150232, -2.095504],
    ]).addTo(mymap);

    var robertGordonCollege = L.polygon([
        [57.147822, -2.1032177],
        [57.147868, -2.100663],
        [57.148858, -2.101521],
        [57.149638, -2.103066],
        [57.149381, -2.104053]
    ]).addTo(mymap);

    var robertGordonCollege = L.polygon([
        [57.147822, -2.1032177],
        [57.147868, -2.100663],
        [57.148858, -2.101521],
        [57.149638, -2.103066],
        [57.149381, -2.104053]
    ]).addTo(mymap);

    var aberdeenBeach = L.polygon([
        [57.142428, -2.068863],
        [57.145315, -2.073669],
        [57.153602, -2.078819],
        [57.164122, -2.079248],
        [57.173149, -2.077446],
        [57.158536, -2.078047],
        [57.147829, -2.074614],
        [57.1428, -2.06809]
    ]).addTo(mymap);


    var victoriaPark = L.polygon([
        [57.15256, -2.124707],
        [57.150599, -2.123762],
        [57.151966, -2.118838],
        [57.152781, -2.119181]
    ]).addTo(mymap);

    var westburnPark = L.polygon([
        [57.155969, -2.126412],
        [57.152664, -2.124674],
        [57.152845, -2.121574],
        [57.153648, -2.121187],
        [57.153625, -2.119911],
        [57.154934, -2.120233]
    ]).addTo(mymap);

    var aberdeenHarbour = L.polygon([
        [57.14536, -2.095031],
        [57.145803, -2.093743],
        [57.146263, -2.087681],
        [57.144526, -2.075472],
        [57.142011, -2.069764],
        [57.140498, -2.075686],
        [57.140498, -2.089033]
    ]).addTo(mymap);


    var aberdeenUniversity = L.polygon([
        [57.166762, -2.106467],
        [57.167129, -2.10224],
        [57.166721, -2.097305],
        [57.16575, -2.097702],
        [57.164498, -2.097402],
        [57.164557, -2.099805],
        [57.163067, -2.099869],
        [57.163266, -2.102047],
        [57.161973, -2.101736],
        [57.162404, -2.10429],
        [57.16337, -2.107208],
        [57.165404, -2.106156],
    ]).addTo(mymap);

    var hazleheadPark = L.polygon([
        [57.142869, -2.17643],

        [57.139067, -2.172997],
        [57.137635, -2.177374],
        [57.137013, -2.180786],
        [57.139591, -2.183726],
        [57.140953, -2.176816],
        [57.142502, -2.178082]
    ]).addTo(mymap);


    /*Display lat/long coordinates - Development use only! */
    var popup = L.popup();
    function onMapClick(e) {
        popup
            .setLatLng(e.latlng)
            .setContent(e.latlng.toString())
            .openOn(mymap);
    }
    mymap.on('click', onMapClick);


    /*Popups*/
    robertGordon.bindPopup("Robert Gordon University");
    pittodrie.bindPopup("Pittodrie Stadium");
    duthiePark.bindPopup("Duthie Park");
    unionTerraceGardens.bindPopup("Union Terrace Gardens")
    marischalCollege.bindPopup("Marischal College and Dancing Water Fountains")
    robertGordonCollege.bindPopup("Robert Gordon College and Art Gallery")
    aberdeenBeach.bindPopup("Aberdeen Beach")
    unionSquare.bindPopup("Union Square")
    victoriaPark.bindPopup("Victoria park")
    westburnPark.bindPopup("Westburn Park")
    hazleheadPark.bindPopup("Hazlehead Park")
    aberdeenUniversity.bindPopup("Aberdeen University")
    aberdeenHarbour.bindPopup("Aberdeen harbour")
        .addTo(mymap);
</script>

1 Ответ

0 голосов
/ 08 мая 2020

Это работает с библиотекой turf js: <script src="https://cdn.jsdelivr.net/npm/@turf/turf@5.1.6/turf.js"></script>

Создание шестигранной формы:

var hex = createHex(myMap.getCenter(),radius); //replace center with navigator point

function createHex(center,radius) {
        var centerp = turf.point([center.lng, center.lat]);
        var points = [];
        points.push(turf.destination(centerp, radius, 90));
        points.push(turf.destination(centerp, radius, 150));
        points.push(turf.destination(centerp, radius, -150));
        points.push(turf.destination(centerp, radius, -90));
        points.push(turf.destination(centerp, radius, -30));
        points.push(turf.destination(centerp, radius, 30));

        var hex = L.polygon([]);
        points.forEach((p)=>{
            hex.addLatLng([p.geometry.coordinates[1],p.geometry.coordinates[0]]);
        });
        return hex;
    }

Чтобы удалить шестигранник из «тумана»:

var fog = L.rectangle([[54.98652836571122, -1.542469837492442],[ 54.973032422136875, -1.4963848081781708]]);
var fogLayer = L.geoJSON(fog.toGeoJSON()).addTo(myMap);

function subtract() {
        var radius = 0.01;
        var hex = createHex(myMap.getCenter(),radius); //replace center with navigator point
        var templayer = L.geoJSON(turf.difference(fogLayer.getLayers()[0].toGeoJSON(), hex.toGeoJSON()));
        fogLayer.removeFrom(myMap);
        fogLayer = templayer.addTo(myMap)
    }

Пример: https://jsfiddle.net/falkedesign/6a4smLgt/

Надеюсь, вы не забыли проверить ответ;)

...