1
votes

In the Leaflet Tutorials (http://leafletjs.com/examples/geojson/) they show how to associate a Marker or a Feature with a pop up - which can contain HTML code.

I would like the user to be able to specify a specific popup to load using a URL. In the Leaflet Tutorial the URL http://leafletjs.com/examples/geojson/example.html loads a map and Features - but none of the popups appear until the user clicks on a Feature.

Is there a way to associate a URL (say) http://leafletjs.com/examples/geojson/example.html#Coors%40Field with a specific Feature so that it displays automatically when the user specifies the URL?

1

1 Answers

5
votes

It's a bit difficult to interpret what you're exactly asking, but it seems to me that you want to open a popup automatically when the hash portion of the location of the current document matches some property of a geographical feature.

So instantiate your layers, then loop through the features of your GeoJSON using L.GeoJSON.eachLayer(), checking if the name matches the hash:

var group = L.geoJSON(geojson, {...}).addTo(map);

group.eachLayer(function(layer) {
    if ('#' + layer.feature.properties.name === document.location.hash) {
        layer.openPopup();
    }
});

Several things to keep in mind:

  • Store a reference to the instance of L.GeoJSON so you can manipulate it (call its eachLayer() method).
  • When L.GeoJSON instantiates a leaflet layer (a L.Marker, L.Polyline or L.Polygon), it will store the GeoJSON feature as a property of the newly created layer, thus layer.feature.
  • The hash portion of document.location is a string that always starts with #. You should clean it up beforehand, paying extra attention to URL encoding.