1

I'm trying to implement maps into a website using Leaflet.js, but I've ran into a problem. Every tutorial I can find passes an ID to the Leaflet map function, like this:

In HTML:

<div id="mapid"></div>

In JavaScript:

var mymap = L.map('mapid').setView([51.505, -0.09], 13);

The website I'm working on has a search function which queries a database and then returns a list of matching organizations. Most (but not all!) organizations have an address associated with it, and I'm trying to generate a map for each address.

So, I can't have a single div with an ID (because I need multiple divs), and I can't just name them "map1", "map2", "map3", etc. because it's dynamic: the number of maps needed is different each time.

Right now, in the search result template I have a map div with a CLASS of "map", but I can't get Leaflet to work with this.

How can I get Leaflet to work in this situation (using a class instead of an ID)?

1
  • So? Fetch the organizations' IDs as well, and create each <div> with a DOM ID based on each organization's ID. Stuff doesn't need to be numerically consecutive. Commented Oct 10, 2020 at 22:02

1 Answer 1

1

The Leaflet documentation shows that the 1st argument of L.map factory can be directly an HTML Element (instead of a string representing the Element ID):

https://leafletjs.com/reference-1.7.1.html#map-l-map

L.map(<HTMLElement> el, <Map options> options?)

Instantiates a map object given an instance of a <div> HTML element

That way, you do not have to choose any unique ID, and just build your map with the Element you just created.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.