0

I watch the visitors position and stores the current coordinates in two variables, latitude and longitude. When the visitor clicks on the map, the new marker's coordinates will be stored in another two variables, click_latitude and click_longitude.

When this is done, I want to show the marker's coordinates in the span .test as text. The problem is that coordinates_click (which contains click_latitude and click_longitude) are always empty! The coordinates for the marker are only stored in the variables within map.on('click', function(e1) { ... } and can not be accessed outside the function.

Why and how can I fix this?

if(navigator.geolocation) {

    // VARIABLES
    var gps_timeout = 10 * 1000 * 1000;


    // MAP
    map = L.map('map', {
        maxZoom: 17,
        minZoom: 7
    }).setView([59.380767, 13.503022], 13);

    // MAP (copyright)
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: 'Map data © OpenStreetMap contributors'
    }).addTo(map);


    // GPS
    navigator.geolocation.watchPosition(success, error, {
        enableHighAccuracy: true,
        timeout: gps_timeout,
        maximumAge: 0
    });


    // ADD MARKER
    map.on('click', function(e1) {

        // IF
        if(typeof(marker) === 'undefined') {
            marker = new L.marker(e1.latlng).addTo(map);

            var position = marker.getLatLng();
            var click_latitude = position.lat.toFixed(6);
            var click_longitude = position.lng.toFixed(6);
            map.panTo(new L.LatLng(click_latitude, click_longitude));

        // IF
        } else {
            marker.setLatLng(e1.latlng);

            var position = marker.getLatLng();
            var click_latitude = position.lat.toFixed(6);
            var click_longitude = position.lng.toFixed(6);
            map.panTo(new L.LatLng(click_latitude, click_longitude));
        }

    });


// IF
} else {
    // error handler
}



function success(position) {

    // VARIABLES
    latitude = position.coords.latitude.toFixed(6);
    longitude = position.coords.longitude.toFixed(6);
    coordinates_current = latitude + ',' + longitude;
    coordinates_click = window.click_latitude + ',' + window.click_longitude;


    // IF
    if(coordinates_click !== '') {
        $('.test').text(coordinates_click);
    }

}

If you want to try, please go to https://erik-edgren.nu/map. The code above is updated to the current code. Please see the my answer below.

Airikr
  • 6,258
  • 15
  • 59
  • 110
  • You can declare `click_` vars globally, outside of the function. Then just drop `var click_` from your functions. Or, access them from the function with `window.click_ = ...`. – randomir Jul 02 '17 at 23:27
  • Ok. I added `click_latitude, click_longitude` under `var gps_timeout = ...` and got this error message: `Uncaught ReferenceError: click_latitude is not defined` – Airikr Jul 02 '17 at 23:28
  • In which line? What environment/browser you use? Have you tried accessing them through `window`? – randomir Jul 02 '17 at 23:33
  • After line 4 in the code in my question. After that, I tried to remove line 5 that I added (as mentioned) and changed the line 62 from `var click_latitude, click_longitude;` to `window.click_latitude;` on line 62 and `window.click_longitude;` for line 63. This gave me the same error message: `Uncaught ReferenceError: click_latitude is not defined` – Airikr Jul 02 '17 at 23:35
  • Does the error message say in which line is the error? – randomir Jul 02 '17 at 23:40
  • Yes: `success @ map:265`. That line is this one: `coordinates_click = click_latitude + ',' + click_longitude;`. I tested to remove line 62 and 63 and changed line 66 (as in my code in my question, which I have updated to the current code) to this: `coordinates_click = window.click_latitude + ',' + window.click_longitude;`. The error message was completely gone after that, but `coordinates_click` says `undefined,undefined`, even after I clicked on the map :/ – Airikr Jul 02 '17 at 23:45
  • Please see the link for further tests in my updated question. – Airikr Jul 02 '17 at 23:47
  • 1
    Ok, so you should always assign to `window.click_ = ...` in your `map` functions, and then read from `window.click_` in your `success` function. You should also remove `var click_` declarations from all functions. – randomir Jul 02 '17 at 23:53
  • Thank you. I've change all `... click_` to `window.click_` but it shows the same: `undefined,undefined`. **EDIT** Hm. the coordinates will be updated upon tab switch in Google Chrome. – Airikr Jul 02 '17 at 23:57
  • Now your `latitude` is undefined in line `directions_(latitude + ..`. You should use a debugger (in Chrome for example, see [here](https://developers.google.com/web/tools/chrome-devtools/)). – randomir Jul 03 '17 at 00:07
  • Thank you for noticing that. I will take a look at it when I have got some sleep :) Many thanks for your help. – Airikr Jul 03 '17 at 00:09
  • 1
    You are welcome. I posted an answer to summarize the solution of your problem. – randomir Jul 03 '17 at 00:30

1 Answers1

0

So, you are declaring click_latitude and click_longitude local to your event functions (map click handler and success function). var declarations always have a function scope.

If you wish to share a variable between several functions, you can use a closure (see also this answer):

$(document).ready(function() {
    var click_latitude, click_longitude;
    ...
    map.on('click', function(e1) {
        click_latitude = ...
        click_longitude = ...
    }
    ...
    function success(position) {
        var coordinates_click = click_latitude + ',' + click_longitude;
        $('.test').text(coordinates_click);
    }
}

or a global variable (property of the window object):

$(document).ready(function() {
    ...
    map.on('click', function(e1) {
        window.click_latitude = ...
        window.click_longitude = ...
    }
    ...
    function success(position) {
        var coordinates_click = window.click_latitude + ',' + window.click_longitude;
        $('.test').text(coordinates_click);
    }
}
randomir
  • 17,989
  • 1
  • 40
  • 55