
Blog
Leaflet is an open source javascript library for interactive maps. While it is designed to be as simple to use as possible, you can extend Leaflet functionality by using external plugins. There are several plugins you can use for geocoding with Leaflet. The example below will show you how to create a simple geocode request for a Leaflet map using the free TravelTime Search API.
This geocoder allows users to visualise their search results as pins on a map, as well as having a list view of addresses. It is available to be integrated into your app or website.
To start geocoding for Leaflet using this free geocoder, you’ll first need to request a TravelTime API key.
This example will show you how to geocode a location string to coordinates and show the location on the map.
All of this will be done in a single HTML document using a Leaflet map library, jQuery for sending AJAX requests and the TravelTime Search API.
First we need to create a HTML template:
In the header, we import Leaflet’s CSS template and JavaScript library as well as jQuery. The single <div> element will contain the map.
To make the example easier, we set the name for the location as a variable inside the code. In real world use that will most likely typed into the search bar by the user.
The TravelTime API authenticates using headers so we will need to include those too:
Now we can send a request to the Geocoding API. It is a very simple GET request that requires only a 'query' field containing the name of the location. You can view a reference in the TravelTime Search API Geocoding documentation.
In the success parameter, we reference a function that draws a marker on the map using the coordinates returned by the API. Here is the code:
Finally we just call the 'sendGeocodingRequest’ function to run everything. The full code can be found here.
Use CodePen to start testing now. You will need to sign up for a free API key.
See the Pen Geocoding for Leaflet by TravelTime (@traveltime) on CodePen.
The TravelTime API can do many things as well as free geocoding:
To start using the TravelTime geocoder sign up for an API key. To learn more about geocoding for Leaflet, get in touch.