Home > other >  Is there any possible way to get lat & long through locate control with marker in leaflet?
Is there any possible way to get lat & long through locate control with marker in leaflet?

Time:03-21

I had the control located css & js ready, but I can't figure it out. I was plan to make it when the located button is pressed, it will located me to the current direction with marker and auto fill lat & long in my web form(As attached).

lat & long form

Below was my existing code for search control. Function auto fill & marker lat/long when search address was found.

<script type="text/javascript">
var mymap = L.map(\'dvMap\').setView(['. $pin_lat . ', ' . $pin_long . '],13);
L.tileLayer(\'https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_all/{z}/{x}/{y}{r}.png\',{maxZoom: 18,attribution: \'\'}).addTo(mymap);
var markerz = L.marker([' . $pin_lat . ', ' . $pin_long . '],{draggable:
true}).addTo(mymap);
var searchControl   =   new L.Control.Search({url:
\'//nominatim.openstreetmap.org/search?format=json&q={s}\',jsonpParam:
\'json_callback\',
propertyName: \'display_name\',propertyLoc:
[\'lat\',\'lon\'],marker: markerz,autoCollapse: true,autoType:
true,minLength: 2,});
searchControl.on(\'search:locationfound\', function(obj) {      
    var lt  =   obj.latlng   \'\';
    var res = lt.split("LatLng(" );
    res = res[1].split( ")" );
    res = res[0].split( ","
);
document.getElementById(\'map_lat\').value = res[0];
document.getElementById(\'map_long\').value = res[1];
});

mymap.addControl( searchControl );
markerz.on(\'dragend\', function (e) {
        document.getElementById(\'map_lat\').value =
        markerz.getLatLng().lat;
        document.getElementById(\'map_long\').value =
        markerz.getLatLng().lng;
});
</script>

I want to make another similar function with locate control

CodePudding user response:

According to the docs, you can use the native Leaflet event locationfound:

map.on('locationfound',(e)=>{
    console.log(e);
    document.getElementById(\'map_lat\').value = e.latlng.lat;
    document.getElementById(\'map_long\').value = e.latlng.lng;
    // if you want, you can trim the number
    document.getElementById(\'map_long\').value = e.latlng.lng.toFixed(6);
})

Here an example on jsfiddle. There the Location search works.

  • Related