2

I'm wondering how can I get lat and lon out of the function in a variable with global scale in Leaflet. The code to get the coordinates per click in the map works fine but then I can't write my lat and lon in global variables. My code which doesn't work look like this:

var lat;
var lon;

function clickEvent(e) {

        if (typeof(newMarker)==='undefined'){
            newMarker = new L.marker(e.latlng, { draggable: true });
            newMarker.addTo(satMap);}
        else { newMarker.setLatLng(e.latlng);}


        lat = e.latlng.lat;
        lon = e.latlng.lng;
}

satMap.on('click', clickEvent);
document.write(lat);
1
  • 1
    If code in your app is as in example above it behaves correctly. When statement document.write(lat); is executed variable lat is undefined since map has not been clicked yet. Whatever you want to do with lat and lon variables has to be trigerred from inside clickEvent or has to happen after the event.
    – TomazicM
    Commented Feb 22, 2018 at 18:50

3 Answers 3

2

I think you need to attach your function to a click event with .on('click').

For example:

var lat;
var lng;

map.on('click', function(e) {
    console.log(e.latlng);  //So you can see if it's working
    lat = e.latlng.lat;
    lng = e.latlng.lng;
});

There are different ways you can implement the function to include other things (like placing markers), but the main point in your case is the layer.on('click') part, otherwise it's not listening for a click. There are some good examples in this tutorial.

4
  • Unfortunately, if I test it by the document.write (lat); statement out of the function, the variable lat is still undefined.
    – user114969
    Commented Feb 22, 2018 at 0:11
  • If you edit your question to include that part of the script someone might be able to help with that part.
    – Evan
    Commented Feb 22, 2018 at 0:23
  • @user114969 it is undefined after you click on the map ?
    – Shiko
    Commented Feb 22, 2018 at 1:40
  • unfortunately yes
    – user114969
    Commented Feb 22, 2018 at 9:21
1

TomazicM was right, to demo this, your Global is populated but you show undefined because it runs before your click is finished. I modified your code to show you. By putting a function call after Lat, lon is defined by your function you can see it's values are really changed.

var lat;
var lon;

function clickEvent(e) {

        if (typeof(newMarker)==='undefined'){
            newMarker = new L.marker(e.latlng, { draggable: true });
            newMarker.addTo(satMap);}
        else { newMarker.setLatLng(e.latlng);}


        lat = e.latlng.lat;
        lon = e.latlng.lng;
        console.log(lat + " Inside");
        now();
}

satMap.on('click', clickEvent);
console.log(lat + " Global");

function now(){
    console.log(lat + " Global after click");
}
1
  • Ah, got it. I have to call the variables in a function afterwards. Thank you so much for your hints. You saved my Master Thesis :-)
    – user114969
    Commented Feb 25, 2018 at 16:38
0

You just need use layer.getLatLngs(); Example : var coordinates in this link (jsfiddle) is your answer:

<!DOCTYPE html>
<html>
<head>
    <title>Leaflet.draw drawing and editing tools</title>

    <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" />
    <script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>

<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.draw.css" />
<script src="https://unpkg.com/[email protected]/dist/leaflet.draw.js"></script>

</head>
<body>
    <div id="map" style="width: 900px; height: 400px; border: 1px solid #ccc"></div>
    <button id="changeColor">Rectangle -> Blue</button>
    <script>
        var osmUrl = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
            osmAttrib = '&copy; <a href="http://openstreetmap.org/copyright">OpenStreetMap</a> contributors',
            osm = L.tileLayer(osmUrl, {maxZoom: 18, attribution: osmAttrib}),
            map = new L.Map('map', {layers: [osm], center: new L.LatLng(51.509, -0.08), zoom: 14 });

        var drawnItems = new L.FeatureGroup();
        map.addLayer(drawnItems);

        var polyLayers = [];

        var polygon1 = L.polygon([
            [51.509, -0.08],
            [51.503, -0.06],
            [51.51, -0.047]
        ]);
        polyLayers.push(polygon1)

        var polygon2 = L.polygon([
            [51.512642, -0.099993],
            [51.520387, -0.087633],
            [51.509116, -0.082483]
        ]);
        polyLayers.push(polygon2)

        // Add the layers to the drawnItems feature group 
        for(layer of polyLayers) {
            drawnItems.addLayer(layer); 
        }


        // Set the title to show on the polygon button
        L.drawLocal.draw.toolbar.buttons.polygon = 'Draw a   polygon!';

        var drawControl = new L.Control.Draw({
            position: 'topright',
            draw: {



                marker: false
            },
            edit: {
                featureGroup: drawnItems,
                remove: false
            }
        });
        map.addControl(drawControl);

        map.on('draw:created', function (e) {
            var type = e.layerType,
                layer = e.layer;

            if (type === 'marker') {
                layer.bindPopup('A popup!');
            }

            drawnItems.addLayer(layer);
      var cordinates =        layer.getLatLngs();

      console.log(cordinates);
        });

        map.on('draw:edited', function (e) {
            var layers = e.layers;
            var countOfEditedLayers = 0;
            layers.eachLayer(function(layer) {
                countOfEditedLayers++;
            });
            console.log("Edited " + countOfEditedLayers + " layers");
        });



        L.DomUtil.get('changeColor').onclick = function () {
            drawControl.setDrawingOptions({ rectangle: { shapeOptions: { color: '#004a80' } } });
        };




    </script>
</body>
</html>
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.