Search Bar Example
A demo for the Search API to add a search bar to a map.
Select Country
HTML Code
The below example uses the Search API, and some functions from the Slpy JS library, to power a search bar and fly to its results.
Also available from NPM with npm install slpy
. See the Slpy JS Github for more info.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Hello World!</title>
<!-- CSS -->
<link href="https://api.slpy.com/lib/slpy/latest/slpy-style.css" rel="stylesheet">
<link href="https://api.slpy.com/lib/mlgl/latest/maplibre-gl.css" rel="stylesheet">
<!-- JS -->
<script src="https://api.slpy.com/lib/slpy/latest/slpy.js"></script>
<script src="https://api.slpy.com/lib/mlgl/latest/maplibre-gl.js"></script>
</head>
<body>
<!-- Example Styling for Map and Search Bar -->
<style>
.map {
width: 100%;
height: 400px;
}
.api-search {
width: 275px;
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.1);
border-radius: 0.25rem;
border: 0px;
margin: 10px 0 0 10px;
background: #fff;
}
#api-search-input {
width: calc(100% - 35px);
padding: 10px;
border-radius: 0.25rem;
border: 0px;
font-size: 14px;
pointer-events: auto;
}
#api-search-input:focus {
outline-width: 0;
outline: none;
}
</style>
<div id="map" class="map"></div>
<script type="text/javascript">
//first, customize settings and initialize the map
//map settings
const apiKey = 'your_api_key';
const targetDivId = 'map';
const country = 'global'; //change to target country for better matching
const latitude = '38.0'; //latitude of your map center
const longitude = '-100.0'; //longitude of your map center
const startZoom = '3';
//initalize the map, and move default map controls to bottom-right
const center = [longitude, latitude];
const map = slpy.maplibreMap({
apiKey: apiKey,
container: targetDivId,
center: center,
zoom: startZoom,
navControl: 'bottom-right'
});
//Second, lets add a basic search box using MapLibre's control class
function searchBarControl() {}
searchBarControl.prototype.onAdd = function(map) {
this._map = map;
this._container = document.createElement('form');
this._container.id = 'api-search-form';
this._container.classList.add('api-search');
this._container.innerHTML = '<input placeholder="City or Postcode" id="api-search-input">';
return this._container;
};
searchBarControl = new searchBarControl();
map.addControl(searchBarControl, 'top-left');
//Here we take the input and perform a request to the Search API.
//Then we take the result and run Slpy JS Markers and flyTo
var markers = [];
map.on('load', function() {
document.getElementById("api-search-form").addEventListener("submit", async (event) => {
event.preventDefault();
if (!document.activeElement.matches("input")) return;
const search = document.getElementById("api-search-input").value;
try {
const response = await fetch(`https://api.slpy.com/v1/search?country=${country}&key=${apiKey}`, {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
body: new URLSearchParams({ query: search })
});
if (!response.ok) throw new Error("Network response was not ok");
const obj = await response.json();
slpy.removeMarker(markers, 0);
if (obj.lat) {
markers = [{ name: "", data: [obj.lat, obj.lon] }];
slpy.addMarkers(markers, map);
slpy.flyTo(obj, map);
} else {
alert("Location not found. Please check your spelling and try again.");
}
} catch (error) {
console.error("Fetch error: ", error);
alert("There was an error processing your request. Please try again later.");
}
});
});
</script>
</body>
</html>
Geocoding Reference
Visit the Search and Geocoding Documentation for more information about settings and features.
Next Steps
Enhance your search with Maps or Autocomplete
Search & Geocoding
- Add a search bar to your map.
- Translate addresses to coordinates
- Search for points of interest.
Maps
- Display your location
- Provide context to an address
- Add popups for more information