Leaflet Day 8 - Zoom to Feature

In this post we’ll add a zoom button to pan the map to one of the towns in the trail stops layer.

Adding a Dropdown Box and Button

The first thing to do is add the select element and a button to the HTML:

  <select id='zoombox'>
  </select>
  <input type="button" id="zoomTo" value="Zoom to town">

We’ll populate the options for the select element using the town GeoJSON.

Creating a Dictionary and Populating the Select Box

Next we loop through the towns in the GeoJSON layer and create a dictionary that maps the town name to its data, then add each as an option to a select element:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
  selectbox = document.getElementById('zoombox');

  var featuremap = {};

  for (var i = 0; i < trail_stops['features'].length ; i++){
      feature = trail_stops['features'][i];
      //console.log(feature['properties']['feature_na']);
      featuremap[feature['properties']['feature_na']] = feature['properties'];
      var opt = document.createElement('option');
      opt.value = feature['properties']['feature_na'];
      opt.innerHTML = feature['properties']['feature_na'];
      selectbox.appendChild(opt);

  }

Line 1 gets the select element in the HTML.

Line 3 declares the dictionary to hold the options for the select box.

In lines 5–12 we loop through each feature in our trail_stops GeoJSON layer and populate the feature map, using the town name as the key (line 8).

Remove the comment from line 7 if you want to see each feature displayed in the JavaScript console.

Lines 9–12 setup the select box with the name of each town.

Wiring Up the Button

We need setup the onclick event and define a function in our JavaScript file to do the actual work:

1
2
3
4
5
6
7
document.getElementById('zoomTo').onclick = zoomToTown;

function zoomToTown(){
    key = selectbox.value;
    obj = featuremap[key];
    map.setView([obj['prim_lat_d'], obj['prim_lon_1']], 9);
}

Line 1 sets up the onclick event to call zoomToTown when the button is clicked.

Line 4 gets the current value from the dropdown box and in line 5, we use it to fetch the feature object.

Using the arcane field names prim_lat_d and prim_lon_1, the map.setView function sets the view and the zoom level (9)

The result gives us the map with a dropdown box and button below it. Select a town from the list and click the Zoom to town button and the map will pan to the new location.

You can view the map live here.

To view the complete source code, view the source of the leaflet_day8.html in your browser, then click on the /code/leaflet/leaflet_d8.js link.