【问题标题】:View latlng in popup after moving marker移动标记后在弹出窗口中查看 latlng
【发布时间】:2021-04-23 10:22:00
【问题描述】:

如果初始位置不正确,我还想在移动标记后在弹出窗口中显示 lat 和 lng。 移动标记后是否可以在弹出窗口中查看新坐标?

<script>
    var map = L.map('map').fitWorld();

    L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
        maxZoom: 18,
        attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, ' +
            'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
        id: 'mapbox/streets-v11',
        tileSize: 512,
        zoomOffset: -1
    }).addTo(map);

    function onLocationFound(e) {
        var radius = e.accuracy / 2;
        var myMarker = L.marker((e.latlng), {draggable: true}).addTo(map)
        .bindPopup("You are within " + radius + " " + e.latlng +" meters from this point").openPopup();
        myMarker.on("dragend", function(e){
        var newCoords = e.target.getLatLng().toString();
       });

        L.circle(e.latlng, radius).addTo(map);
    }

    function onLocationError(e) {
        alert(e.message);
    }

    map.on('locationfound', onLocationFound);
    map.on('locationerror', onLocationError);
    map.locate({setView: true, maxZoom: 16});
</script>

【问题讨论】:

    标签: javascript leaflet geolocation latitude-longitude marker


    【解决方案1】:

    您可以再次拨打.binPopup(text)

    var myMarker = L.marker((e.latlng), {draggable: true}).addTo(map)
            .bindPopup("You are within " + radius + " " + e.latlng +" meters from this point").openPopup();
    
    myMarker.on("dragend", function(e){
            var newCoords = e.target.getLatLng().toString();
            myMarker.bindPopup("New Coords: "+newCoords).openPopup();
    });
    

    要将 latlng 拆分为单独的部分,您可以使用 .latlng.lat / .latlng.lng 属性

    myMarker.on("dragend", function(e){
            var latlng = e.target.getLatLng();
            myMarker.bindPopup("New Coords: Lat: "+latlng .lat +" Lng: "+latlng .lng).openPopup();
    });
    

    【讨论】:

    • 非常感谢!如果我想拆分 Lat:xx 和 Long:yy?
    • @CartoLover 我更新了答案。请接受此答案为正确的
    【解决方案2】:

    你可以用 substring(startposition,endposition); 进行拆分

     var lat = newCoords.substring(7, 16);
     var lng = newCoords.substring(17, 27);
     myMarker.bindPopup("New Coords: "+lat +lng).openPopup();
    

    【讨论】:

      猜你喜欢
      • 2016-05-24
      • 1970-01-01
      • 1970-01-01
      • 2020-10-29
      • 1970-01-01
      • 1970-01-01
      • 2014-09-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多