Mapbox теряет всплывающие окна при переключении между просмотром спутников и улиц. - PullRequest
0 голосов
/ 04 августа 2020

В режиме просмотра карты улиц Mapbox мы рисуем географическую json линию и размещаем всплывающие окна в каждой из путевых точек.

При переключении из вида карты улиц на вид со спутника путевые точки исчезают.

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

В чем причина? Как сделать так, чтобы путевые точки отображались на спутниковом изображении.

https://jsfiddle.net/Profiler/a0wemkjz/1/

                        mapboxgl.accessToken = 'pk.eyJ1IjoiY2xvbmc0MCIsImEiOiJjazNpeXV3a3MwY2Y4M2pxbGFybjZ5MTM4In0.HNQRjQR4y5V1koLlpenKUw';
                        var map = new mapboxgl.Map({
                            container: 'map',
                          style: 'mapbox://styles/clong40/ckbdypecg2ev71jqzc0xhdx54', //streetmap view, below is satelite view
                         // style: 'mapbox://styles/clong40/ckd74lwfm0l7f1is3iys2s6qx',
                            center:  [3.1428,39.8669],
                            zoom: 7
                        });
                        
                        // Add geolocate control to the map.
                        map.addControl(
                            new mapboxgl.GeolocateControl({
                                positionOptions: {
                                    enableHighAccuracy: true
                                },
                                trackUserLocation: true
                                },
                                ),'bottom-right'
                            );
                            
                        /* Creates start point marker and listens to drag event */
                        var el = document.createElement('img');
                        el.src = '/assets/images/letter_s.png';
                        var startMarker = new mapboxgl.Marker(el,{draggable: true}).setLngLat([3.1428,39.8669]).addTo(map);
                        function onStartDragEnd() { var lngLat = this.getLngLat();$("#start").val(lngLat.lat.toFixed(4)+','+lngLat.lng.toFixed(4));}
                        startMarker.on('dragend', onStartDragEnd);
                        
                        /* Creates end point marker and listens to drag event */
                        var el = document.createElement('img');
                        el.src = '/assets/images/letter_e.png';
                        var endMarker = new mapboxgl.Marker(el,{draggable: true}).setLngLat([4.0812,40.0724]).addTo(map);
                        function onEndDragEnd() { var lngLat = this.getLngLat();$("#end").val(lngLat.lat.toFixed(4)+','+lngLat.lng.toFixed(4));}
                        endMarker.on('dragend', onEndDragEnd);
                        
                        /* Let's also listen to start and end text boxes to sync back with markers */
                        $(document).ready(function(){
                            $('#start').change(function(){if(!this.value) return; var parts = this.value.split(',');startMarker.setLngLat([parts[1].trim(),parts[0].trim()]);});
                            $('#end').change(function(){if(!this.value) return; var parts = this.value.split(',');endMarker.setLngLat([parts[1].trim(),parts[0].trim()]);});
                        });
                            
                        map.on('load', function() {
                            map.addSource('route', {
                                'type': 'geojson',
                                'data': {
                                    'type': 'Feature',
                                    'properties': {},
                                    'geometry': {
                                        'type': 'LineString',
                                        'coordinates': [
                                                                                [3.1428091990252,39.866845647036],
                                                                                [3.14265625,39.866640625],
                                                                                [3.1425,39.8665625],
                                                                                [3.141875,39.8671875],
                                                                                [3.14375,39.869375],
                                                                                [3.2,39.91],
                                                                                [3.89,40.08],
                                                                                [4.0812,40.0724],
                                                                                ]
                                    }
                                }
                            });


                            map.addLayer({
                                'id': 'route',
                                'type': 'line',
                                'source': 'route',
                                'layout': {
                                    'line-join': 'round',
                                    'line-cap': 'round'
                                },
                                'paint': {
                                    'line-color': '#333399',
                                    'line-width': 4
                                }
                            });
                        });


                        //add markers

                        map.on('load', function() {
                        map.addSource('places', {
                            'type': 'geojson',
                            'data': {
                                "type": "FeatureCollection",
                                "features": [
                                                                                            {
                                        "type": "Feature",
                                        "properties": {
                                            "icon": "information",
                                            "icon-allow-overlap": true,
                                            "iconSize": "15"
                                        },
                                        "geometry": {
                                            "type": "Point",
                                            "coordinates": [3.1428091990252,39.866845647036]
                                        }
                                    },                                                                      {
                                        "type": "Feature",
                                        "properties": {
                                            "icon": "information",
                                            "icon-allow-overlap": true,
                                            "iconSize": "15"
                                        },
                                        "geometry": {
                                            "type": "Point",
                                            "coordinates": [3.1425,39.8665625]
                                        }
                                    },                                                                      {
                                        "type": "Feature",
                                        "properties": {
                                            "icon": "information",
                                            "icon-allow-overlap": true,
                                            "iconSize": "15"
                                        },
                                        "geometry": {
                                            "type": "Point",
                                            "coordinates": [3.14375,39.869375]
                                        }
                                    },                                                                      {
                                        "type": "Feature",
                                        "properties": {
                                            "icon": "information",
                                            "icon-allow-overlap": true,
                                            "iconSize": "15"
                                        },
                                        "geometry": {
                                            "type": "Point",
                                            "coordinates": [3.89,40.08]
                                        }
                                    },                                   
                                ]
                            }
                        });
                        // Add a layer showing the places.
                        map.addLayer({
                            'id': 'places',
                            'type': 'symbol',
                            'source': 'places',
                            'layout': {
                                'icon-image': 'information',
                                'icon-size': 0.10,
                                '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 = '';
                        });
                    });


                        map.addControl(
                            new MapboxGeocoder({
                                accessToken: mapboxgl.accessToken,
                                mapboxgl: mapboxgl
                            }), 'top-left'
                        );


            

                        var map = new mapboxgl.Map({attributionControl: false})
                        .addControl(new mapboxgl.AttributionControl({
                        compact: true
                        }));

                        var canvas = map.getCanvasContainer();

                        map.addControl(new mapboxgl.NavigationControl(), 'bottom-right');

               ```

1 Ответ

1 голос
/ 06 августа 2020

Глядя на консоль, когда я переключаюсь на спутниковый стиль, я вижу следующее:

Не удалось загрузить "информацию" изображения. Убедитесь, что вы добавили изображение с помощью map.addImage () или свойства «спрайт» в вашем стиле. Вы можете предоставить отсутствующие изображения, прослушивая событие карты styleimagemissing.

Это относится к map.addSource('places', ...), где вы устанавливаете "icon": "information"

Используя API стилей, вы можете проверьте наличие различных спрайтов, которые есть в ваших стилях: https://docs.mapbox.com/api/maps/#retrieve -a-sprite-image-or- json

вы можете увидеть в спрайтах для вашего первого стиля , что у вас есть спрайт под названием «информация».

это отсутствует в вашем спутниковом стиле

в вашем JSFiddle, я поменял все ссылки «информация» на "information-15" (спрайт, который существует в обоих стилях) и изменил размер значка на 1 в вашем addLayer, и смог переключаться между стилями и отображать значки в обоих

map.addSource('places', {
    'type': 'geojson',
    'data': {
      "type": "FeatureCollection",
      "features": [{
        "type": "Feature",
        "properties": {
          "icon": "information-15",
          "icon-allow-overlap": true,
          "iconSize": "15"
        },
        "geometry": {
          "type": "Point",
          "coordinates": [3.1428091990252, 39.866845647036]
        }
      }, {
        "type": "Feature",
        "properties": {
          "icon": "information-15",
          "icon-allow-overlap": true,
          "iconSize": "15"
        },
        "geometry": {
          "type": "Point",
          "coordinates": [3.1425, 39.8665625]
        }
      }, {
        "type": "Feature",
        "properties": {
          "icon": "information-15",
          "icon-allow-overlap": true,
          "iconSize": "15"
        },
        "geometry": {
          "type": "Point",
          "coordinates": [3.14375, 39.869375]
        }
      }, {
        "type": "Feature",
        "properties": {
          "icon": "information-15",
          "icon-allow-overlap": true,
          "iconSize": "15"
        },
        "geometry": {
          "type": "Point",
          "coordinates": [3.89, 40.08]
        }
      }, ]
    }
  });
  // Add a layer showing the places.
  map.addLayer({
    'id': 'places',
    'type': 'symbol',
    'source': 'places',
    'layout': {
      'icon-image': 'information-15',
      'icon-size': 1,
      'icon-allow-overlap': true
    }
  });
...