如何拖动自定义图标Mapbox GL JS

时间:2016-09-28 17:46:05

标签: mapbox mapbox-gl mapbox-gl-js

我目前正在使用Mapbox GL JS,我有custom icons like this example,我希望能够拖动图标。

我这样做与draggable point example类似,我有mouseDownonMoveonUp个函数。但是我卡住的部分在onMove,我不知道如何设置自定义图标,div在整个拖动过程中更新其位置。我正在更新图标的新坐标(lng& lat),但我不确定如何实际移动它们,因为图标不会移动/拖动。

在原始的可拖动点示例中,它有map.getSource('point').setData(geojson);更新geojson以允许点在地图上移动。

所以基本上我只想在Mapbox GL JS中拖动自定义图标。

感谢。

1 个答案:

答案 0 :(得分:1)

我遇到了类似的问题,经过几个小时后,设法将两个示例结合起来并将坐标导出到表单字段中。试试这个片段(使用你自己的accessToken,地图样式和标记图像)

$(document).ready(function() {
    // ===============================================
    // mapbox
    // ===============================================
    // Holds mousedown state for events. if this
    // flag is active, we move the point on `mousemove`.
    var isDragging;

    // Is the cursor over a point? if this
    // flag is active, we listen for a mousedown event.
    var isCursorOverPoint;

  
  
mapboxgl.accessToken = '############# Add your own accessToken here ##########';
    var map = new mapboxgl.Map({
        container: 'map-one',
        style: 'mapbox://############# Add your own style here ##########',
        center: [5.037913, 52.185175],
        pitch: 0,
        zoom: 12
    });
    
    var nav = new mapboxgl.Navigation({
        position: 'top-left'
    });

    map.addControl(nav);

    var canvas = map.getCanvasContainer();

    var geojson = {
        "type": "FeatureCollection",
        "features": [{
            "type": "Feature",
            "geometry": {
                "type": "Point",
                "coordinates": [5.067, 52.1923]
            },
			"properties": {
				"title": "Afspreekpunt",
				"marker-symbol": "dimmle-marker"
			}
        }]
    };

    function mouseDown() {
        if (!isCursorOverPoint) return;

        isDragging = true;

        // Set a cursor indicator
        canvas.style.cursor = 'grab';

        // Mouse events
        map.on('mousemove', onMove);
        map.on('mouseup', onUp);
    }

    function onMove(e) {
        if (!isDragging) return;
        var coords = e.lngLat;

        // Set a UI indicator for dragging.
        canvas.style.cursor = 'grabbing';

        // Update the Point feature in `geojson` coordinates
        // and call setData to the source layer `point` on it.
        geojson.features[0].geometry.coordinates = [coords.lng, coords.lat];
        map.getSource('point').setData(geojson);
    }

    function onUp(e) {
        if (!isDragging) return;
        var coords = e.lngLat;

        canvas.style.cursor = '';
        isDragging = false;

        // Update form fields with coordinates
        $('#latitude').val(coords.lat);
        $('#longitude').val(coords.lng);
    }


    // Mapbox map-accordion fix
    $('#accordion').on('hidden.bs.collapse', function () {
        map.resize();
    })
    $('#accordion').on('shown.bs.collapse', function () {
        map.resize();
    })


    // After the map style has loaded on the page, add a source layer and default
    // styling for a single point.
    map.on('load', function() {

        // Add a single point to the map
        map.addSource('point', {
            "type": "geojson",
            "data": geojson
        });

        map.addLayer({
            "id": "point",
            "type": "symbol",
            "source": "point",
            "layout": {
              // ##############################################
              // NOTE: this is my marker, change it
              // to the marker you uploaded in your map style
              // - you will likely need different 
              //   offset/translate values
              // ##############################################
				"icon-image": "my-marker",
                "icon-size": 0.3,
				"text-field": "",
				"text-offset": [0, 0.6],
				"text-anchor": "top",
                "text-size": 14
			},
			"paint": {
                "icon-translate": [-6, -34],
			}
        });

        // If a feature is found on map movement,
        // set a flag to permit a mousedown events.
        map.on('mousemove', function(e) {
            var features = map.queryRenderedFeatures(e.point, { layers: ['point']         });

            // Change point and cursor style as a UI indicator
            // and set a flag to enable other mouse events.
            if (features.length) {
                canvas.style.cursor = 'move';
                isCursorOverPoint = true;
                map.dragPan.disable();
            } else {
                //map.setPaintProperty('point', 'circle-color', '#3887be');
                canvas.style.cursor = '';
                isCursorOverPoint = false;
                map.dragPan.enable();
            }
        });

        // Set `true` to dispatch the event before other functions call it. This
        // is necessary for disabling the default map dragging behaviour.
        map.on('mousedown', mouseDown, true);


    });
}); // end document ready
.map { border: 1px solid #ccc }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
   <script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.25.1/mapbox-gl.js'></script>
    <link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.25.1/mapbox-gl.css' rel='stylesheet' />

<div id='map-one' class='map' style='height: 360px;'></div>
<input id="latitude"> <input id="longitude">