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.
Simple geocoding request
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, native JavaScript AJAX calls jQuery for communicating with TravelTime Search API.
STEP 1: Create and import templates
First we need to create a HTML template:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Geocoding for Leaflet</title>
</head>
<body>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet/v1.3.0/leaflet.css" />
<link rel="stylesheet" href="css.css" />
<script src="https://unpkg.com/leaflet@1.4.0/dist/leaflet.js" integrity="sha512-QVftwZFqvtRNi0ZyCtsznlKSWOStnDORoefr1enyq5mVL4tmKB3S/EnC3rRJcxCPavG10IcrVGSmPh6Qw5lwrg==" crossorigin=""></script>
</head>
<body>
<div id="mapid"></div>
<div id="error" class="">
<p><b>No API and APPLICATION_ID key inserted </b></p>
<p><a target="_blank" href="http://docs.traveltimeplatform.com/overview/getting-keys/">Sign up for an API key</a>
<p>Place it in API and APPLICATION_ID variables</p>
</div>
<script>
// all code will go here
</script>
<style>
// all style will go here
</style>
</body>
</html>
In the header, we import Leaflet’s CSS template and JavaScript library as well as jQuery. The single <div>
element will contain the map.
STEP 2: Set location name
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.
STEP 3: Add headers
The TravelTime API authenticates using headers so we will need to include those too:
var locationName = "Tour Eiffel, Paris, France";
var APPLICATION_ID = "place your app id here";
var API_KEY = "place your api key here";
STEP 4: Send request
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.
function sendGeocodingRequest(location) {
return fetch(`https://api.traveltimeapp.com/v4/geocoding/search?query=` + location, {
method: "GET",
credentials: "same-origin",
headers: {
"Content-Type": "application/json",
"X-Application-Id": APPLICATION_ID,
"X-Api-Key": API_KEY
}
})
.then(response => response.json()); // parses JSON response into native Javascript objects
}
STEP 5: Draw markers
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:
function drawMarker(response) { // We need to extract the coordinates from the response.
var coordinates = response.features[0].geometry.coordinates; // The coordintaes are in a [<lng>, <lat>] format/
var latLng = L.latLng([coordinates[1], coordinates[0]]) // The url template for OpenStreetMap tiles.
var osmUrl = "http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"; // Creates the tile layer.
var osmTileLayer = L.tileLayer(osmUrl, {
minZoom: 8,
maxZoom: 15
}); // Adds the tile layer to the map.
var map = L.map("mapid").addLayer(osmTileLayer);
map.setView(latLng, 11); // Creates a marker for our departure location and adds it to the map.
var markter = L.marker(latLng).addTo(map);
};
The full code
Finally we just call the `sendGeocodingRequest’ function to run everything. The full code can be found here.
Live code editor environment
Use CodePen to start testing now. You will need to sign up for a free API key.
About the TravelTime API
The TravelTime API can do many things as well as free geocoding:
- Display where's reachable within a time limit on a map, based on the mode of transport
- Calculate a travel time matrix (often called a distance matrix) from an origin to thousands of destinations
- A to B routing
To start using the TravelTime geocoder sign up for an API key. To learn more about geocoding for Leaflet, get in touch.
Top comments (0)