user663724
user663724

Reputation:

Leaflet : Map container is already initialized

The User types some address (Hyderabad,Telanagna) on text field and clicks on Go button

I am fetching the latitude_res and longitude from google Map API as shown below

$(document).on('click', '.gobtn', function(event) {
    $.getJSON('https://maps.googleapis.com/maps/api/geocode/json?address=' + address + '', function(data) {
        latitude_res = data.results[0].geometry.location.lat;
        longitude_res = data.results[0].geometry.location.lng;
    }).done(function() {
    });

});

I am able to fetch the latitude and longitude , from google API say for example i got the following values

**17.385044
78.910965**

Then i am making a Ajax call again to fetch all the Markers present at this location in our Database .

And finally initializaing the map as shown below

initializeMap(lator,lonor,markers);


function initializeMap(lator, lonor, markers) {

    var map = new L.Map('map_canvas', {
        center: new L.LatLng(lator, lonor),
        zoom: 5 
    });
    var ggl = new L.Google();
    var ggl2 = new L.Google('ROADMAP');
    map.addLayer(ggl2);
    if (markers.length > 0) {
        var markers_leafcontainer = new L.MarkerClusterGroup();
        var markersList = [];
        for (var i = 0; i < markers.length; i++) {
           var lat = parseFloat(markers[i].latitude);
            var lng = parseFloat(markers[i].longititude);
            var trailhead_name = markers[i].address;
            var dealerId = markers[i].dealerID_db;
            var dealername = markers[i].dealerName_db;
            var contentString = "<html><body><div><p><h2>" + dealername + "</h2></p></div></body></html>";
            var marker = L.marker(new L.LatLng(lat, lng), {}).on('click', onClick);
            $(".howmanyfound").text(markers.length + ' Found');
            markers_leafcontainer.addLayer(marker);
        }
        map.addLayer(markers_leafcontainer);
        map.fitBounds(markers_leafcontainer.getBounds()); //set view on the cluster extent

    }     
    }

Only for the first time this is working , from there on i am getting Uncaught Error: Map container is already initialized.

I am using leaflet with google Maps

Upvotes: 1

Views: 14300

Answers (1)

Jonatas Walker
Jonatas Walker

Reputation: 14168

So, don't initialize the map inside your function.

var map = new L.Map('map_canvas');
initializeMap(lator,lonor,markers);

function initializeMap(lator, lonor, markers) {
    map.setView(L.latLng(lator, lonor));


}

Upvotes: 7

Related Questions