0

I'm working with Leaflet maps and I want to use a button to change the marker positions. The problem is that my map is initialized.

Uncaught Error: Map container is already initialized.

I've been reading some posts, but I can't do it correctly.

This one, suggests using this line before initialize the map but it's not working (probably I'm doing it wrong) document.getElementById('issMap').innerHTML = "<div id='map'></div>";.

Some others solutions suggest using map.remove() but it is not working as well.

Reading the leaflet's documentation I think I just have to remove a layer and put another one, but I don't know-how.

My code,

function mapa(coords){

    centerMap_coords = centerMap(coords)

    if (map != undefined) { map.removeLayer(); } //Not working
    var map = L.map("issMap", {
        center: [centerMap_coords[0], centerMap_coords[1]],
        zoom: 13,
        gestureHandling: true
    });
    const attribution = '&copy;<a href="https://www.openstreetmap.org/copyright/">OpenStreetMap</a> contributors';
    const tileUrl = 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
    const tiles = L.tileLayer(tileUrl, {attribution}).addTo(map);

$('#btn_map').click(function(){
    if( $('#ultima_posicion_check').is(':checked') ) {
        var coords = [37.363,2.336];
        mapa(coords);

    }else if($('#ruta_ultimas_posiciones_check').is(':checked')){
        var coords = [39.321,2.258];
        mapa(coords);

    } else{
        alert('Checkbox empty');
    }

Thank you!

Lleims
  • 1,275
  • 12
  • 39

1 Answers1

0

If you want to change the position from the map use map.setView([lat,lng]) or map.panTo([lat,lng]).

If you want to change the position from a marker use this:

var marker = L.marker([39.321,2.258]).addTo(map);

function clickOnMap(){
marker.setLatLng([37.363,2.336]);
}

You can place the marker at the postion where clicked with that:

map.on('click', function(e){
marker.setLatLng(e.latlng);
//Or new marker:
//L.marker(e.latlng).addTo(map);
});
Falke Design
  • 10,635
  • 3
  • 15
  • 30