Home » Code » Creating An Interactive Map With Leaflet and OpenStreetMap
      

Creating An Interactive Map With Leaflet and OpenStreetMap

posted by Andy Maloney

I’ve known for a while that the interactive map of the world showing some of my bloodstain pattern analysis software customers was kind of slow. I also knew that I was using a very outdated version of Google’s API for displaying the data. Yesterday I decided to take a look at it to see what I needed to do to fix it up.

Old Google Map

Old Google Map

My first stop was the Google page about moving to v3 of the API. Apparently I needed to get a new API key by signing up for something with my Google Account. Google has added usage limits and now tracks absolutely everything (yes, they probably did before, but now it’s more explicit). I also needed to consider whether or not I can use the maps on a commercial site.

I don’t like hurdles, and I like simplicity, so I decided to look around for alternatives. I remembered looking at OpenStreetMap (OSM) several years ago when I originally built my map and deciding it wasn’t quite good enough. I decided to check it out again to see how they were doing. My how things change!

OpenStreetMap

OpenStreetMap

Because I’m a good lazy developer (by that I mean I avoid writing things when they already exist, are well-coded, and maintainable), my first thought was to grab a WordPress plugin and to use it for my map. I tried out the OSM – OpenStreetMap plugin. While it sort-of worked for what I was trying to do, it was not as customizable as I’d like, it seemed too heavy for one map on one site, and it tied me to WordPress (which my other site hasn’t moved to yet).

My next thought was to look for a JavaScript library with a nice API to integrate and handle most of the heavy lifting. Poking around the OSM site, I ran across OpenLayers. It looked pretty powerful, and has a ton of stuff in its API. I downloaded it (10M?) and took a look but I really just wanted something simpler. Then I found Leaflet. Exactly what I needed. Small, simple, great documentation, and some really straightforward examples.

Leaflet

Leaflet

Even though I had to brush up on some JavaScript, jQuery, and JSON concepts—things I rarely use— I ended up researching possibilities and replacing my Google Map with an OpenStreetMap/Leaflet version in just a couple of hours. It’s now much faster and simpler to customize.

New OpenStreetMap/Leaflet Map

New OpenStreetMap/Leaflet Map

In this article, I’ll step through an example that shows how to:

  • set up a simple map using the Leaflet JavaScript library
  • load marker locations from a JSON file
  • change the marker icon
  • have the markers show some data when clicked

As an example, I’m going to create a map showing the countries I’ve lived in or travelled through for a month or more. The example consists of three files and two images:

  • index.html – the page itself
  • maps/leaf-demo.js – JavaScript to create the map and populate it with markers
  • maps/markers.json – a list of markers with their latitude & longitude and a url to display
  • maps/images/pin24.png and pin48.png – the pin to display (one for normal display, one for retina)

(The files used in this example are available on github.)

The HTML

Let’s start by taking a look at the HTML.

This file starts out with standard HTML header stuff, so the first interesting lines are these:

These lines pull in the CSS and JavaScript libraries we need to display and work with the maps. In this example, we are linking to these files stored on a remote server using a CDN. Another option would be to host these files ourselves, but the advantages of using these CDNs are:

  1. lightens the load on your server
  2. CDNs distribute the content so it’s closer to the user, resulting in faster downloads
  3. browsers limit the number of HTTP requests to each host, so accessing multiple, different hosts allows fetching data in parallel, resulting in faster display of the page (we’ll see this idea again with the tiles which make up the map)
  4. if a user has visited another site using the same script, it may already be in the user’s cache resulting in no download at all and faster display of the page

This example uses cdn.leafletjs.com to get the Leaflet CSS and library and ajax.googleapis.com to get the jQuery library. Note that leaving the protocol off the Google URL is not an error – this is a protocol relative URL (a.k.a. scheme-less URI).

(Update: I was using MAMP to write and test this. It’s the web server which adds the correct protocol to scheme-less URIs, so if you just open the file on its own, browsers will not add it properly. You will need to add http: to the ajax.googleapis.com URI for this to work. I have updated the download to fix this.)

The next interesting part of this HTML file is this div:

We’re creating a div called “map” with a height and a border. This is the div that is going to be filled in with our map when we create it in our JavaScript. If we do not specify a width, it will adjust the width of the map to the page dynamically.

The last part of this file is the key. This is where we load the JavaScript that does the work of setting up and displaying our map.

The first script is a JSON file with our marker information and the second is the code to setup and display our map. Note that the second script has to come after the map div is created so the JavaScript has something to target. In this case, we’re loading a local file, so let’s take a look at that next.

The Leaflet JavaScript

Our initial JavaScript is pretty straightforward. All we are doing here is creating the map and adding a tile layer. The tile images are coming from the OpenStreetMap servers which are good for testing. Note that they say on their site:

Apart from very limited testing purposes, you should not use the tiles supplied by OpenStreetMap.org itself.

This creates a new map, assigns it to the ‘map’ div and sets some options. In this case we are centering the initial view at 20° latitude and 5° longitude, setting the minimum zoom level to 2 and the default zoom level to 2. There are many other options you can set here to tweak the way you want your map displayed.

This code adds a layer to the map telling it what set of tiles to display and where to get them. There are several different servers you can use – or you can host your own.

Again, Leaflet has many options to use when creating a tileLayer. In our example, the first argument is the URL template so Leaflet knows how to fetch the tiles from the servers properly. Next is the attribution – this is what shows up in the bottom-right corner of the map. It is important that you add the right info here for proper attribution of the tile set.

Finally we have a list of subdomains. This array of strings is substituted into the {s} portion of the URL template. Note that this list depends on the tile servers you are using. This option allows a browser to download from several servers at the same time (remember I mentioned this when explaining CDNs above?) which results in faster loading of the page and faster updates as the user drags around the map. One of the problems I had with the old Google solution is that it only used one server, so it was slow. This capability makes it much faster.

OK, so now we have an interactive map we can drag around and zoom in and out. Let’s add some markers to it.

The JSON Data

Although it is possible to put the marker data right in with our JavaScript file, I like keeping my data in a separate file so it’s easy to swap out or update without modifying the main file.

For this example, I’m using JSON as a little database to store the country name, Wikipedia url, and longitude and latitude of each of the countries I’ve either lived in or travelled through for a month or more.

To read this data and add the markers to our map, I just loop over the array and call the Leaflet function to create markers:

Leaflet’s markers offer many options for customization. In our example, we are creating a marker at a specific location, binding a simple popup to it, and adding it to our map. The latitude and longitude and the data to display in the popup (the country name and link to Wikipedia) are read from our JSON file.

So far, so good, but those markers are kind of big, so let’s swap them out for our own icons.

Changing The Icon

I found a free pin icon over at clker.com that I thought would look good on this map. I played around a bit with different sizes and settled on a height of 24 pixels. I created two versions: the regular version with a height of 24 pixels and a double-sized version for retina displays with a height of 48 pixels. And of course I ran these through ImageOptim to compress them as much as possible.

Since we are going to add our own icon, the code we did in the last section needs to be changed a bit. Here’s what we have now:

In this code, the first thing I’m doing is grabbing our URL and removing the file name so I can create a URL for the icons. Not being a JavaScript guru, I’m not 100% sure this is the best way to do this, and it feels hacky, but it does work. (If you know of a better way, please contact me!)

The next line declares a var myIcon to hold our new icon. Leaflet’s icon allows you to specify all sorts of things, but the key ones are the ones we use here. The iconUrl, iconRetinaUrl, and iconSize options are self-explanatory. The iconAnchor is the pixel location in the icon file that corresponds to the specific latitude and longitude. The popupAnchor specifies where the popup should be located relative to the iconAnchor.

One last thing to do with our new icon is actually apply it. To do that, we simply add it as an option when creating our markers {icon: myIcon} (line 24).

Voilà!

Final Result

Here’s our final result – an interactive map indicating the countries I’ve either lived in or travelled through for a month or more.

I hope this is useful to someone out there in internet-land!

As always, if you have suggestions on how to improve my code or make things easier, please comment below or feel free to contact me.

Project Files: The files used in this example are available on github.

Update 10 June 2015: If you end up with too many markers on your map, consider using Leaflet.markercluster to cluster them!

Update 12 July 2016: MapQuest discontinued the tile set I was using, so I switched to OpenStreetMap’s tiles. Note that these are useful only for testing. They say on their site:

Apart from very limited testing purposes, you should not use the tiles supplied by OpenStreetMap.org itself.

Update 12 July 2016: Updated example to use Leaflet 0.7.7 (no code changes, just including newer version of javascript).

130 Comments

  1. Comment by Robert:

    Hi Andy,
    thanks for the tutorial – just a short remark: you might be interested in also trying another WordPress OSM plugin: search for “Leaflet Maps Marker” in the WordPress plugin repository (free version) or download the pro version from http://www.mapsmarker.com – my plugin allows users to pin, organize & show your favorite places & tracks through OpenStreetMap, Google Maps, KML, Bing Maps, APIs or Augmented-Reality browsers
    best regards,
    Robert

    • Comment by Andy Maloney:

      Thanks Robert.

      Your plugin is obviously very comprehensive and has tons of neat features – overkill for what I was doing! Besides which I needed to embed this in a non-WordPress site too.

      If I ever need more complicated maps I’ll be sure to try it out though.

  2. Comment by HieuT:

    Very simple and nice tutorial. Thanks Andy!

  3. Comment by SamG:

    This tutorial was EXACTLY what I needed to kickstart my new project, thanks a lot!

  4. Comment by Jose Ricardo Borba:

    Very nice tutorial. Simple and effective. Thanks for your time and effort to help others (like me!).

  5. Comment by steflp:

    Hello,

    Very good tuto !
    With you example , you use a the world map , I want to use a part of map ( region , country ) how can i do that ?

    Best regards …

    • Comment by Andy Maloney:

      If you mean using a different, smaller set of tiles for a region, I think you could just substitute them in when creating the tile layer (see the Javascript code calling L.tileLayer()).

      If you mean using one of the provided tile sets and restricting the view to a specific region, then in the Javascript code where you create the map (just under the The Leaflet JavaScript heading) you can set the location to the region you want and play with the minZoom and maxZoom options to restrict it.

      Is that what you mean?

  6. Comment by Krupa:

    Hi Andy,

    Very useful post.
    I have data for Germany with below latitudes and longitudes
    var markers = [
    {
    “lat”: 16.32595,
    “lng”: 47.39564
    },
    {

    “lat”: 16.34755,
    “lng”: 47.39189
    },

    {

    “lat”: 16.40003,
    “lng”: 47.42923
    }
    The problem i am facing is only one marker is visible on the map, may be because the value difference between the markers latitude and longitude is very less.

    I am using the center point same as that of yours with values [20 , 5]

    Any idea what could be the issue ?

    Thanks,
    Krupa

    • Comment by Andy Maloney:

      …may be because the value difference between the markers latitude and longitude is very less.

      I bet this is the case – the points are very close. When you are zoomed out all the way, they will overlap.

      I can’t test it myself right now, but what happens when you zoom in to the area, do you see all three of them?

  7. Comment by Krupa:

    Sorry, below is my data for the latitude and longitude
    var markers = [
    {

    “lat”: 47.39564,
    “lng”: 16.32595
    },
    {

    “lat”: 47.39189,
    “lng”: 16.34755
    },

    {

    “lat”: 47.42923,
    “lng”: 16.40003
    }

    • Comment by Andy Maloney:

      Krupa:

      If I add the missing closing bracket ]; at the end of your data, and paste that into the example’s markers.json file, the three points show up on the map when I open the example and zoom in.

      Maybe there’s something else wrong in your code?

  8. Comment by Krupa:

    FYI

    I have placed the above code in an aspx page and i am calling the Initialize() method on body onload

    Thanks,
    Krupa

    • Comment by Andy Maloney:

      I’m afraid I can’t tell what’s wrong with your code. I would suggest starting with the example, replacing the JSON with yours, making sure that works for you, and then adding in the new code bit-by-bit to figure out what’s not working for you.

  9. Comment by Tristan:

    hi
    Awesome tutorial ! thanks Andy.

    I’m (french) not a developper.

    Was wandering if we can load the list of all the markers beside the map with a link to it on the map using the markers.json file ?

  10. Comment by Menashe:

    Thank you very much for this great information!
    I’ve done an extensive search and I still wonder how can I let users define a bounding box on the map, to be used as a geo filter for a search form.

    Thanks.

  11. Comment by Menashe:

    Thank you Andy. I’ve decided that presenting a rectangle control for letting the user select a bounding box using Leaflet or OpenLayers is nice, but doesn’t worth the effort (I’ve found how to do it).Instead, I’m telling the user that holding down the shift key while dragging the mouse can be used for selecting a bbox. I’ve added a popup which tells the user what are the current LatLon values, while the shift key is pressed.
    Upon zoomend: The selected area occupies all the redrawn map, and I have the coordinates using map.getBounds().getNorth(), etc.
    Upon mouseup: map.closePopup();

    I hope these details can help someone.

  12. Comment by semirk123:

    thank you a lot sir. you cannot know how much you helped me

    best from turkey

  13. Comment by AB:

    Hi, Andy! Thanks for the tutorial, it’s helped a lot. This is my first experience using JSON at all, so I was wondering if you could help me out with the pop-ups my markers.json file outputs.

    Currently I have Name | URL | Lat | Long for each marker, exactly like in your tutorial. But if I’d like any other text to my pop-up, it seems like I need to add into the “name”, perhaps with a little html syntax. But it’s still linked the marker’s URL. Any suggestions? Thanks again.

    • Comment by Andy Maloney:

      If I understand your question correctly, you want to be able to put different information in the popup?

      The key line is this one (line 25 under the heading Changing The Icon above):

      You can add whatever you want in the JSON file, so you might have something like this:

      and then use it like this:

      (Untested code, but should point you in the right direction.)

  14. Comment by Chris Baze:

    I want to attempt something very similar to this, but with the added ability to let any user add their own pins for new projects (the site will on a LAN, not the internet). What would be the easiest way to add this functionality?

    • Comment by Andy Maloney:

      Chris:

      Doing this requires some form of persistent storage for the data. This could be reading & writing the JSON file itself or storing it in a database.

      How you approach it would depend on what languages and tools you have available, how robust you want your solution to be, the scope of the project (how many locations? how many people accessing it?, etc.), and how much time & effort you want to put into it.

      Using a database—if you have one available—would probably be the safest and easiest solution. Then you don’t have to worry about multiple people trying to update the same file on the filesystem at the same time…

      • Comment by Chris Baze:

        OK, and if I wanted the .json file/markers to point to a folder on a server within our domain instead of a URL like your example, how do I make this change in the .json file? BTW great tutorial! I am in way over my head but you made a non-coder feel really smart 😀

        • Comment by Andy Maloney:

          Thanks Chris.

          The first thing I would try for that kind of setup is:

          On the web server create a link to the file somewhere within your htdocs or wherever your web pages are served from. How you do this is dependent on what kind of system you are working on.

          Then change this line to reference that URL:

          Alternatively – and I’m not 100% sure this would work:

          Drag the file to the browser and you should get a file:// URL – something like file:///path/to/markers.json.

          Put that in as the src in that script tag.

          This would mean (I think) that everyone would have to have the server folder mounted in the same way.

  15. Comment by flavius:

    Do you know if it is possible to make produce dynamic clustered markers in Openstreetmap just like in Google Maps?
    Example:
    http://component.kitchen/components/google-map-markerclusterer

    Thanks!

  16. Ping from Mapping Workshop – Resources | ajantriks:

    […] Andy Maloney – Creating an Interactive Map with Leaflet and OpenStreetMap. […]

  17. Comment by Zofren:

    Excellent tutorial. It will allow me to start my new map-based project with something working ! Thank you !

  18. Comment by Ignacio G. del Valle:

    This is a great tutorial, should be linked from the leaflet.js tutorial’s page. Thank you very much!!

    I am looking for a way to let users set their own markers and store them (either locally or on a central repository). Any hint about how to do it, or where to look?

    Regards,

    • Comment by Andy Maloney:

      Ignacio:

      As I mention in a comment above, doing this requires some form of persistent storage for the data. This could be reading & writing the JSON file itself or storing it in a database.

      I assume you want this available to the internet, not just an intranet (as in the comment above). I think if I were approaching this problem, I would create a little REST API and use it from javascript to read & update markers.

      Hope that helps and points you in the right a direction.

  19. Comment by Toms:

    How about license, can i use this for commercial. not for letting people pay but just set markers where the forests are ore something like that?
    Thanks

    • Comment by Andy Maloney:

      My code doesn’t have a license – you can do whatever you want with it.

      Leaflet and OpenStreetMap have their own license as do any tile sets you use, so you will have to look into that. My understanding is that they just require a note with links on the map, but thankfully I am not a lawyer.

  20. Comment by Akanksha Kumar:

    This tutorial is the best one that i have come across. It is very simple, clear and precise. And the example is very simple and basic which makes understanding the code very easy.

    Thank you so much for this blog. It was very helpful. Keep it up.

  21. Comment by Kristin:

    Andy… I wouldn’t make it through my final project at code school without this tutorial! Thank you so much!

  22. Comment by Ranjeet Kumar:

    Hi Andy,
    your post was so use full. it has worked so nice.
    Could you please suggest me how to apply mouse over and click event on marker of leaflet map.

    Regards,
    Ranjeet

  23. Comment by eduzal:

    thank you, this is what i need for a kickstart. this simple tutorial is what I was looking for.
    I had to make a small change in the iconsURLs, had to make it relative to the index: “maps/images/pin24.png”. since i’m not using mump, the jquery wasn’t working.

  24. Comment by kanav:

    thanks for sharing your brilliant example with us.
    i have understood how to put markers on desired locations usina a JSON file.

    but my query is.
    if i am searching for places from for ex. -google maps. we get markers for those locations. this same thing i want to implement in here, such that i will get data in lat and long for places, how to add markers for those places ?

    • Comment by Andy Maloney:

      This is beyond the scope of this tutorial, but I would start by looking at the Leaflet documentation to see how to manipulate the map using the API.

      Once you have the lat and lng for the point it should be a simple matter of adding a marker using the same javascript methods outlined in this tutorial.

  25. Comment by Nikhil:

    Hi Andy, thanks for a brilliantly explained tutorial.
    I’m wondering : How can one go about converting a simple excel csv /tsv having the same kind of data : place name, a link, longitude and latitude; and importing that here? Is there a way to convert spreadsheet data into the JSON format you used? Because it’s much simpler for humans to make the table than a JSON.

    • Comment by Andy Maloney:

      You can either convert it to JSON “offline” then just use the JSON, or you might consider modifying the code to just read CSV files and convert to JSON using Javascript. It depends on if you need to do it once or multiple times.

      To do the former, you can use an online tool like Mr. Data Converter to convert online.

      To convert using Javascript, you might look for a library like PapaParse.

  26. Comment by david:

    Hello ,very good tutorial , but unfortunately Mapquest is not very open :/

    http://info.mapquest.com/mapquest-terms-of-use-ca-en/

    and maybe i’m bad (^^) but i had no sucess with anoter “maper” ,if you have one idea for …

    Thanks,

    • Comment by Andy Maloney:

      Without knowing what level of “open” you’re comfortable with or what specifically about the terms you don’t like it’s hard to recommend anything.

      As far as I’m aware, there are no other free/open tile sets. The OSM ones themselves, while CC-licensed, are not meant to be used in the wild:

      “Apart from very limited testing purposes, you should not use the tiles supplied by OpenStreetMap.org itself.”

      (See switch2osm – Using Tiles for more info.)

      If you have the resources, you could create your own tiles. Then you’d have total control over “openness”.

  27. Comment by pradeep:

    i just want to know how to add markers and display route between them on map… so i can get direction between markers

  28. Comment by pascale:

    hi,

    thanks very much.. so simple but..
    when i add this line

    i get error “Uncaught TypeError: Cannot read property ‘replace’ of undefined”

    and without this line i get this error : Uncaught ReferenceError: markers is not defined

    any idea ? thanks

    • Comment by Andy Maloney:

      Pascale:

      You will need to replace leaf-demo.js in this line with whatever you named your javascript file.

      This is a little hack to get the URL so we can use it to find out images for the icons. I’m sure there’s a better way to do this, I just haven’t spent the time to figure it out.

  29. Comment by Peter Hofer:

    Thank you very much for this detailed tutorial and for sharing your experience with us. Best wishes.

  30. Comment by pascale:

    Thanks for your answer
    i don’t want use icon actually, just try to work with simple one with markers.

    and with this code below, i have error : Uncaught ReferenceError: markers is not definedmap.js?ver=1:36 (anonymous function)

    do you see where is the problem ? THANKS

    • Comment by Andy Maloney:

      It’s almost impossible to debug these things when just looking at small snippets of code.

      It’s telling you that markers isn’t defined, so check that you’ve defined it somewhere. I put it in the ‘maps/markers.json’ file which is included earlier – see the code at the bottom of The HTML section above.

      The javascript debugger in Chrome might help you figure this kind of thing out.

  31. Comment by pascale:

    Thank you Andy
    the prob came from the order i call different scripts in my page

  32. Ping from Basic leaflet map | Aysha Khan:

    […] originally created the map markers and pop-ups in the JS file, but following Andy Maloney’s example, I made a separate JSON mini-database and then looped through the array via the […]

  33. Comment by Nikhil:

    I had the same chain of experience as your discovery of Leaflet : Finding google too troubling, checking out OSM, checking out OpenLayers and hitting a wall there, and later on finding Leaflet. Now I’m working on leaflet, being able to do many more things with it and loving it.

  34. Comment by JB:

    Excellent tutorial, exactly what I needed and works perfectly! Ah there is always a but… json isn’t supported on IIS6 which is where I ultimately need to host this project. Could you point me in the right direction on changing this side of things? Many thanks.

    • Comment by Andy Maloney:

      json isn’t supported on IIS6…

      I’m assuming this means that IIS6 won’t serve files with a json extension?

      Since I worked on the tutorial about clustering markers in Leaflet, I realized that what I’ve got here is slightly semantically incorrect. It’s not technically a JSON file. If you look at the other tutorial, the markers are simply served as a javascript file which assigns the variable.

      Maybe that would help in your case?

  35. Comment by Giyan:

    Hello Andy , nice tutorial . It helps me a lot.
    But i have a question , how to show a popup when the user hover the marker ?
    Im sorry if this is a silly question , im new in javascript.

  36. Comment by Soon Hoieik:

    It’s a good tutorial Andi but now i have problem can u help me to make search marker in my map?

  37. Comment by Muhammad Usman:

    Thank you very much for this detailed tutorial and for sharing your experience with us. Best wishes.

  38. Comment by Zsolt Takacs:

    Thank you so much for this tutorial, it was extremely useful and easy to follow. Wishing you the best from Hungary.

  39. Comment by Soumaya:

    Hello,

    Thank you very much for this tutorial. It is really what I need but I have to pick out my latitude and longitude from Mysql database and plot them in the map.

    Do you have any advice to do this?

    Thank you so much,

  40. Comment by Rubel:

    This is really a great example and also helpful discussion after that….I like it…I am doing my masters thesis and might need some help…I will ask later. this time just a Thankx for this tutorial….

  41. Comment by Jeison Santiago:

    Very nice tutorial mate! Thanks for sharing!

  42. Ping from Mapa interactivo web con Leaflet para mostrar un geojson, editado con Brackets y publicado en Github | másquesig:

    […] este post me he basado en este artículo publicado y sobretodo en los tutoriales de la web oficial de […]

  43. Comment by Siddhartha Gupta:

    Very useful tutorial. Another advantage of using a CDN to fetch js libraries is that they supply minified versions (min.js) which are compressed and transfer fast.

  44. Comment by matt:

    Andy!

    Great tutorial, and after a few days of looking at many ‘tutorials’ yours is by far the most concise and easy to understand.

    I still cannot get this to work though… I am using WAMP to test on. I have a working map in [code][/code]

    All my other coding is as yours except for the file refs.

    No markers showing at all…?

    Any ideas?

    • Comment by Andy Maloney:

      Matt:

      (Your code didn’t show up in your comment. I think you can just use <code></code> in a comment.)

      The first thing I would do is check that my example is working as expected. If so, then I would load yours and look at the browser’s JavaScript console to see if there are any errors showing up.

      When you say the ‘file refs’ are different that could easily be the problem. If it can’t find the file with the markers it will still show the map without them.

  45. Comment by Richard Brown:

    Hi Andy

    Just what I needed to get me kick started and even better I can get other folks to be involved in adding markers to the map we are creating. It is very simple. Thanks.

    A quick question though, I have added an image and text to the pop up but there is a max width default to 300. Do you know how I could increase this to 400 please?

    Thanks

    Rich

    • Comment by Andy Maloney:

      Rich:

      You need to set the option maxWidth on the popup. The available options are listed in the leaflet reference.

      It looks like – after a quick scan of the reference – you’ll need to modify the way the popup is added by creating a popup object and adding it to the map like they show in the code example.

  46. Comment by Rory Ru:

    Thanks for such a simple explanation of setting up the map. I’ve been trawling the internet, through many tutorials but this one was perfect. Onto clustering 🙂

  47. Comment by Omkar:

    Hello Andy, I wanted to implement the map in different languages adding them as layers.
    There will be a dropdown and the user can select the language from the dropdown and the places appear in that language in the map. How can I do it??
    Thanks.

  48. Comment by richard:

    Greetings community need help my country is Venezuela ‘m now doing the same for my graduation project and I need to place the names of the streets of the sites displayed on the map , someone could help me

  49. Comment by Tadcoco:

    Very helpful, thanks indeed

  50. Comment by Ramesh:

    Hi..
    This is very useful for my project. I have search some other site but I didn’t got an idea but this is very useful. thanks.
    And I have a doubt…

    What are the other input methods for giving the plotting point like JSON???
    is it possible to take values from Data Base tables??

    • Comment by Andy Maloney:

      What are the other input methods for giving the plotting point like JSON?

      You can use any format you like to store the information. If you wanted to store it as a CSV, you could do that and then modify the JavaScript to parse the CSV and fill in the proper fields. I chose JSON because it is the most natural fit for JavaScript.

      Is it possible to take values from Data Base tables?

      It is, and that would allow you to create a dynamic site – adding and removing points and so on. But this would be a much more complicated program and is beyond the scope of this example.

      If I were going to approach that problem I would create a little REST API server using a language such as Go (or whatever language you’re familiar with – Python, PHP, etc…), connect it to a database such as ArangoDB, and access it from JavaScript to read & update markers.

      • Comment by Ramesh:

        Ok…Thank you…The given information is very useful. And I have one more doubt. I have developed a Web apps with help of your code. The problem is I need to mark the hospitals and important organization in my OSM map. What I will do for show that.

        • Comment by Andy Maloney:

          Given that the whole purpose of this tutorial is placing markers on a map, I think I must be missing some context. Can you explain what you mean? Can’t you just put your hospital names, locations, etc. in the data file?

          • Comment by Ramesh:

            Hi… I have tried your map in my project. It has successfully worked before two weeks but now it show “Direct tile access has been discontinued”. I need this map in my application permanently. What are I will do for that ????

  51. Comment by joe c:

    new map needed:

  52. Comment by Ramesh:

    Hi… I have tried your map in my project. It has successfully worked before two weeks but now it show “Direct tile access has been discontinued”. I need this map in my application permanently. What are I will do for that ????

  53. Comment by vaibhav sharma:

    Hello guys,

    I am trying to create a Mean stack app with leaflet js.i am facing issue to display place name on the map on the basis of latitude and longitude.i have created a connection with mongodb and imported json file into mongodb to retrieve the json data with the help of express and node js but i am confused with what url should i use for ajax call and how i will use the data retrieve from ajax call with leaflet js to display it on map.

  54. Comment by Colin Turner:

    Thank you very for much. I have to admit I have no idea what you are trying to accomplish here:

    Can you not just specify an absolute URL? eg.
    iconUrl: ‘http://myserver.com/markers/marker.png’

    • Comment by Andy Maloney:

      Colin:

      You can use an absolute URL if you like, but it’s usually a bad idea to hardcode a URL like that.

      This code is pulling the leaf-demo.js off the URL so I can reference the file I want using the rest of the URL. This makes it site-independent. I use this code on multiple sites, have moved things around a few times, and switched them to https. Having it hardcoded would just add another thing to change or break.

      Like I said – might not be the best way to do it. I haven’t revisited this in a long time, but I’m sure I could come up with something better.

  55. Comment by Mrityunjay:

    Hi Andy, just need to know how can I achieve offline map using leaflet & osm .mbtiles
    I have tried this approach ,

    1. downloaded .mbtiles file from osm vector tiles
    2. Kept .mbtiles into my asset folder by renaming it to .db so that I can access from sqlite db.
    3. Uses custom leaflet tile layer Leaflet. MBTiles.js to parse tiles and create a tile layer and add it to map object.

    So currently stuck in step 3. Any idea in parsing the tiles from db files and creating tile layer ?
    Thanks in advance.

  56. Comment by Mr Nk:

    Great writeup! Kudos there

    Please which tile can I use in production given that OSM seem not appropriate?

  57. Comment by Balasaheb:

    Thanks for tutorial….

  58. Comment by Dennish:

    Is it possible to make of this for offline uses?

  59. Comment by Robert:

    Thanks for this tutorial Andy! I was having the hardest time following another Leaflet/Mapbox tutorial but then I came across yours. You broke it down easily and I was able to understand the components. After actually being able to see your maps work in my browser, I returned to the other tutorial with a better understanding and was able to make it work

  60. Comment by Geoff:

    Great tutorial – thanks

    I do have a problem

    The copy of Leaflet-Example from GitHub work perfectly from a PC directory. BUT when index.html is run from a web server hosting the same files the map appears fine, but the markers are not displayed?

    I have not been developing JaveScript for long but I have played around with the script. I think the script runs fine until the for loop in leaf-demo.js where it tries to resolve the value of markers.length. My thoughts are that the script ab-ends at this point.

    Am I right that the leaf leaf demo pages can be dropped onto a web server and run unchanged?

    Thanks
    Geoff

  61. Comment by Geoff james:

    Further to my note of earlier. I can see from the debug screen (I am not an expert) that the file ‘markers.json’ is receiving a 404 file not found error.
    That explains why the script abends at the first reference to its contents.
    The file markers.json is certainly on the web. I have also looked at my mod settings and they are all 777 which I believe is fine.
    I have also disabled my anti-virus and firewall and an app or two in Firefox – no change.
    The same fault occurs with Explorer.

  62. Comment by Richard Brown:

    Hi

    Trying to run this in the json file and it gets rejected:
    “details”: “favoriteMusic: ‘<a href=”#” rel=”nofollow”>80s Rock</a>'”,
    I thought the single quotes should be enough. I also tried this:
    “details”: “favoriteMusic: ‘<a>80s Rock</a>'”,
    Any ideas how I might achieve this please?

    Thanks

    Rich

    • Comment by Andy Maloney:

      If I understand your question, it’s about how to use double quotes within double quotes? You can escape them using ‘\’ like this:

      (WordPress is adding the extra rel=”nofollow” – please ignore 🙂

      • Comment by Richard Brown:

        Hi Andy

        I have used the escape in the code but it doesn’t work. This is the site I am working on:
        http://ewh2015.evergreen.software/walking-map-uk-routes-lands-end

        The markers don’t load as soon as I add a link.

        Thanks

        Rich

        • Comment by Andy Maloney:

          I’m seeing links in the marker popups on that site. ?

          Looks like that page inlines the javascript so I inlined it like this in the index.html page and it’s working for me.

          I guess the difference is you aren’t using json to hold the markers anymore. Why not? It’s a lot easier to manage and will make your code shorter.

          Aside: I would suggest not inlining this code – leave it in its own file so it’s easier to manage and can be cached properly. Also there’s an awful lot of redundant code there – I would refactor it. customOptions doesn’t need to redefined over and over again for example.

          • Comment by Richard Brown:

            Thanks for the reply. I unfortunately handed over the coding to another firm. They have changed the code and I am now finding a few issues with it. Not sure what to do next but thanks for all the help.

            Rich

Leave a Reply

Your email address will not be published. Required fields are marked *