Leaflet.js Interactivity II: Allow Users to Add Points

29 Jun

In Part I, I showed how to use buttons to add and remove layers, and how to capture popup text and display it in a <DIV> element. In this post I will show how to allow users to create their own points with popups. Here is an image of the page with no input yet.

First, I created a blank map with just a Cloudemade Tile.

Second, I created a <DIV> to hold my form:

LAT:<input type=”text” id=”lat”>
LONG:<input type=”text” id=”long”>
POPUP:<input type=”text” id=”popuptext” value=”POPUPTEXT”>
<button onclick=”createPoint()”>Create Point</button>

Lastly, I create the function in the form:

function createPoint()
var lat = document.getElementById(‘lat’).value;
var long = document.getElementById(‘long’).value;
var pop = document.getElementById(‘popuptext’).value;
var latint = parseInt(lat);
var longint = parseInt(long);
var mora = new L.LatLng(latint, longint),
MSD = new L.Marker(mora);

To see it working go to EducationalFacilityPlanning.com/UserAddPoints.html

Try typing in 35, -106 for Lat and Long

This needs more work, like a function to allow the user to click on the map and get a long,lat pair:

map.on(‘click’, onMapClick);
var popup = new L.Popup();

function onMapClick(e) {
var latlngStr = ‘(‘ + e.latlng.lat.toFixed(3) + ‘, ‘ + e.latlng.lng.toFixed(3) + ‘)’;

popup.setContent(“You clicked the map at ” + latlngStr);


But, more importantly, a function to save the points so the user can recreate their map.


Happy Hacking



2 Responses to “Leaflet.js Interactivity II: Allow Users to Add Points”

  1. semirk123 July 11, 2014 at 11:43 am #

    thank you a lot sir, i want to save markers permanently. what should i do?

    • paulcrickard July 11, 2014 at 12:37 pm #

      You need to dump them to a database. There is a Leaflet plugin that can help, or, you need to write a function marker.on(“add”, function(e){
      Make ajax call to a server passing e.latlng and have the server save it to your DB});

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: