I am trying to add map markers to my leaflet map, using coordinates returned from a call to an api. I origionally set the map marker to a specific location (leaflet wasnt happy with a blank array), I then update the marker variable when a user selects a country from a drop down list. I can see that the marker variable is being updated after each user selection, but the marker on the map doesnt change location? heres the parts of the JS code involved:
let baseMaps = {
"Hybrid": hybrid,
"Terrain": terrain,
"Streets": streets,
"Sat": sat,
"Pulchritudinous": pulchritudinous,
};
//variable to hold coordinates of marker
let markerTest = L.marker([54, -2]);
let overlayMaps = {
"Marker" : markerTest
};
let map = L.map('map', {
layers: [pulchritudinous, streets, sat, terrain, hybrid, markerTest]
});
//add baselayers to map
L.control.layers(baseMaps, overlayMaps).addTo(map);
here is the api call and return code;
function markers(){
$.ajax({
url: "libs/php/markerCapital.php",
type: 'GET',
dataType: 'json',
data: {
country: country,
},
success: function(result) {
// console.log(JSON.stringify(result, null, 4));
if (result.status.name == "ok") {
console.log("success markerCaptial");
//reset cities array
cities = [];
//populate cities array with data
for(let i = 0; i < result.data.geonames.length; i++){
cities.push([result.data.geonames[i].asciiName, result.data.geonames[i].lat, result.data.geonames[i].lng, result.data.geonames[i].population]);
}
//Add to map
markerTest = L.marker([cities[0][1], cities[0][2]]);
console.log("MARKER TEST: ", markerTest);
}
}
markers() gets called everytime a user changes location.
Found the solution. In the api call response, update markerTest as follows:
markerTest.setLatLng([cities[0][1], cities[0][2]]).update();
console.log("MARKER TEST: ", markerTest);
Not sure its the best way to do it, but it works.