1
votes

I've an issue with the leaflet openPopup method.

showMap = function(elements) {
    var jsonp = 'http://a.tiles.mapbox.com/v3/blahblahblah.jsonp';
    var m = new L.Map("my_map").setView(new L.LatLng(51.5, -0.09), 15);

    var geojsonLayer = new L.GeoJSON();

    var PlaceIcon = L.Icon.extend({
        iconSize: new L.Point(25, 41),
        shadowSize: new L.Point(40, 35),
        popupAnchor: new L.Point(0, -30)
    });

    var icon = new PlaceIcon(__HOME__ + '/images/leaflet/marker.png');
    var marker;


    for (var i = 0; i < elements.length; i++) {
        var address = $("<div/>").html(elements[i].address).text();
        var latlng = new L.LatLng(elements[i].latitude, elements[i].longitude);
        marker = new L.Marker(latlng, {icon: icon}).bindPopup(address);

        if (i == 0) {
            marker.openPopup();
        }
        m.addLayer(geojsonLayer).addLayer(marker);
    }
    // Get metadata about the map from MapBox
    wax.tilejson(jsonp, function(tilejson) {
        m.addLayer(new wax.leaf.connector(tilejson));
    });
}

When I click on a marker I have the popup open. But I would like to have the first popup open when the map is loaded. (and open other popups on markers click)

AnNy ideas ?

3

3 Answers

5
votes

Put openPopup call after you add the marker to the map and you should be fine.

2
votes

I'm assuming that when you click on a marker you see the popup but you're not getting the popup of the first marker to show automatically when the map is loaded?

First, it doesn't look like you're actually using GeoJSON so a GeoJSON layer isn't necessary (you can just use a FeatureLayer) but that shouldn't cause any issues. Whatever layer group you use you should only be adding it to the map once and then adding all child layers to the LayerGroup. You're currently adding the geojsonLayer multiple times in your "for" loop which you don't want to do. Second, you have to call marker.openPopup() after the marker is added to the map. Try changing your code around to looks something like this:

var layerGroup = new L.FeatureGroup();
layerGroup.addTo( m );

for (var i = 0; i < elements.length; i++) {
    var address = $("<div/>").html(elements[i].address).text();
    var latlng = new L.LatLng(elements[i].latitude, elements[i].longitude);
    marker = new L.Marker(latlng, {icon: icon}).bindPopup(address);

    //You don't add the marker directly to the map.  The layerGroup has already
    //been added to the map so it will take care of adding the marker to the map
    layerGroup.addLayer( marker );

    if (i == 0) {
        marker.openPopup();
    }
}
0
votes

First add your map then put openPopup():

L.marker([lat, long]).bindPopup('Your message').addTo(map).openPopup();