leaflet—marker总结

今天公司的app需要完成一个需求:

在地图上通过自己手动添加一个marker点,然后将坐标等数据(经纬度)传给另个方法中,去获取地理编码信息。最后将坐标信息和地理编码信息以及手动添加的相关点数据一起传给后台去存储。并且在查看信息的时候定位到该坐标位置。

分析:

0.按钮触发

1.需要在地图上获取人手点击的位置(经纬度)

2.将经纬度传给marker并在地图上生成

3.并且marker点可以进行拖拽

4.给marker点添加事件进行跳转

 

在网上看见了其他人的教程:

            Leaflet监听点击事件并弹出Popup

https://malagis.com/leaflet-note-10-click-show-lan-lat.html

var map = L.map('map-container').setView([36.52,120.31], 7);

var tileAddress = 'https://api.mapbox.com/styles/v1/yqcim/';
tileAddress += 'cizh1ma3400ez2so5x1anhuzo/tiles/256/{z}/{x}/{y}';
tileAddress += '?access_token=pk.eyJ1IjoieXFjaW0iLCJhIjoiY2l6ZmhnZjEx';
tileAddress += 'MDBhajJ4cGxnNGN5MnhpdCJ9.pcZtdfk8mSFboCdwqkvW6g';

var attribution = 'Map data &copy; <a href="http://openstreetmap.org">';
attribution += 'OpenStreetMap</a> contributors, '
attribution += '<a href="http://creativecommons.org/licenses/by-sa/2.0/">';
attribution += 'CC-BY-SA</a>, ';
attribution += 'Imagery © <a href="http://mapbox.com">Mapbox</a>';

L.tileLayer(tileAddress, {
  maxZoom: 18,
  attribution: attribution,
  id: 'mapbox.streets'
}).addTo(map);

// use event
var mypop = L.popup();
map.on('click', function(e) {
  var content = '你临幸了这个点:<br>';
  content += e.latlng.toString();
  mypop.setLatLng(e.latlng)
       .setContent(content)
       .openOn(map);
});

这里监听事件和前文中的方法一致,使用on方法对地图实例mclick事件做监听。在点击的时候创建一个Popup,然后将Popup内容动态设置成点击位置的经纬度。

Leaflet marker拖拽

https://www.cnblogs.com/CoffeeEddy/p/9975801.html

      var marker1 = L.marker([30.75, 120.75]).addTo(this.map);
      var marker2 = L.marker([30.76, 120.76], { draggable: true }).addTo(this.map);

      //拖拽结束
        marker2.on('dragend', function (event) {
          var position = marker1.getLatLng();
           console.log('实时坐标:' + marker2.getLatLng());
        })
        //marker1.on('moveend ', function (e) {
         //    console.log(e.target._latlng);
        //});

         $('#ctrlDragge').on('change', function () {
             var isCheck = this.checked;
            if (isCheck) {
                 marker1.dragging.enable();
            } else {
                marker1.dragging.disable();
                 console.log(marker1.getLatLng());
            }
        });

结合以上分析

我得出以下代码

     var mypop = L.popup();
    map.on('click', function(e) {
        var content = '你点击了这个点:<br>';
        content += e.latlng.toString();
        var lat=e.latlng.lat;
        var lng=e.latlng.lng;
        mypop.setLatLng(e.latlng)
            .setContent(content)
            .openOn(map);
       var marker =L.marker([lat,lng], { draggable: true }).addTo(map);
        //拖拽结束
        marker.on('dragend', function (event) {
                     console.log('实时坐标:' + marker.getLatLng());
                  })
    });

我使用on对地图触控进行监听

将点击的点坐标传递给marker然后在地图上显示

实现点击后可以拖拽,并记录坐标位置

转载自:https://blog.csdn.net/qq_36213352/article/details/85632103

You may also like...