Search code examples
javascriptjquerymappingglobal-variablesopenstreetmap

jQuery: Creating global variable for a map


So I'm creating a website which adds markers to a map based on the current location of the user using jQuery. I've never used jQuery before so I'm struggling on very basic issues their are two problems I have with the script so far.

1) The map is not a global variable, so in the process position function, I cannot add markers to the map, I assumed that if I created the map variable outside of any function that this would work fine, however I still get an error. I know this is probably a very minor issue but I need to be able to refer to the map variable so I can add markers in other functions.

2) The back $("#back_btn").click(function() was effectively attempting to reset the contents of a division to what it was prior, the change button function changes it to a search script which will search for location the user chooses. Although it resets it fine, more or less, the #change_btn does not work when clicked again, I used the clone method to copy the elements of the form and although the exact same button appeares again or the functionality is gone, why is this the case?

 $(function() {

    var map = L.map ("map1");

    $("#change_btn").hide();

    $("#back_btn").hide();

    var old_form = $("#location_form").clone(); 

    var attrib="Map data copyright OpenStreetMap contributors, Open Database Licence";

    L.tileLayer ("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
                { attribution: attrib } ).addTo(map);

    var lat = 50.908;

    var lon = -1.4;

    var pos = [lat, lon];

    var marker = L.marker(pos).addTo(map);

    map.setView(pos, 6);

    var popup = document.createElement("popup");

    var placeinfo = document.createTextNode("Your current location: " + "Latitude: " + lat + "Longitude" + lon); 

    popup.appendChild(placeinfo);

    if(navigator.geolocation)
    {
        navigator.geolocation.getCurrentPosition (processPosition, handleError);
    }
    else
    {
        alert("Sorry, geolocation not supported in this browser");
    }   

    $("#find_btn").click(function () { 
        if ("geolocation" in navigator){ 
            navigator.geolocation.getCurrentPosition(processPosition, handleError);
        }
        else{
            console.log("Browser doesn't support geolocation!");
        }
    });

    $("#change_btn").click(function(){

        $("#location_form").load("scripts/searchlocation.php");

        $("#back_btn").css("display", "inline-block"); 

    }); 

    $("#back_btn").click(function(){

        $("#location_form").empty();

        $("#location_form").html(old_form); 

        $("#change_btn").css("display", "inline-block"); 

        $("#back_btn").hide();

        $("#find_btn").hide();
    }); 

});

function processPosition(gpspos)
{
    var info = 'Lat: ' + gpspos.coords.latitude + ' lon: ' + gpspos.coords.longitude;

    $("#result").html(info);
    $("#change_btn").css("display", "block"); 
    $("#find_btn").css("display", "none"); 

    var lat = gpspos.coords.latitude;

    var lon = gpspos.coords.longitude;

    alert("Latitude: " + lat + " Longitude: " + lon);

    var pos = [lat, lon];

    var marker = L.marker(pos).addTo(map);

    map.setView(pos, 6);

    var popup = document.createElement("popup");

    var placeinfo = document.createTextNode("Your current location: " + "Latitude: " + lat + "Longitude" + lon); 

    popup.appendChild(placeinfo);

}

function handleError(err)
{
    alert('An error occurred: ' + err.code);
}       

Sorry for these questions, I really appreciate any help that you can give me,

thanks for your time;

Jacques


Solution

  • You're experiencing scope issues because you're effectively defining var map in an anonymous function for the jQuery DOM ready handler.

    Change:

    $(function() {
    
      var map = L.map ("map1");
    
      ...
    });
    

    To:

    var map;
    
    $(function() {
    
      map = L.map ("map1");
    
      ...
    });
    

    so that you can access map globally.