Display Pharmacy addresses on our own interactive map | Using Leaflet & Leaftlet-geosearch Library.
Leaflet is an open library based on OpenStreetMap. It’s a very handy and easy to use tool for developing interactive maps on your website. We start by referencing it’s CSS files in the WordPress header.php.
<!-- Leaflet CSS -->
<link rel="stylesheet" ref="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A==" crossorigin=""/>
<link rel="stylesheet" href="https://unpkg.com/leaflet-geosearch@3.0.0/dist/geosearch.css"/>
we do the same thing for the leaflet js library as well as for the script of our own map in the footer.php.
<script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js" integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA==" crossorigin=""></script>
<!-- Make sure you put this AFtER leaflet.js, when using with leaflet -->
<script src="https://unpkg.com/leaflet-geosearch@3.0.0/dist/geosearch.umd.js"></script>
<!-- Own script for the leaflet map -->
<script src="<?php echo get_template_directory_uri() ?>/assets/js/map.js"></script>
As mentioned above Leaflet is easy to use and has a well-documented API on its official website. The first thing we have to do in order to create our map is to create three containers.
NOTICE!
We have to create all three containers inside the if-statement related to our search form if(isset($_POST[“search”]) ): … endif; as the map will only be shown after our visitors have submitted their search request.
One visible container to display our map itself. This container must have the id “mapid” so that leaflet will be able to locate it.
<div id="mapid" style="min-height:100%;"></div>
The next container will be invisible and only contain the zip code and the city name from our visitor’s search request. This information will later be converted into their geocoordinates by leaflet-geosearch and used to set the view of the map
<div id="zip" class="d-none">
<?php echo $zip_code;?>,
<?php echo $pharmacies[0]["pharmacy_city"]?>,
USA
</div>
The third and last container won’t be displayed either and will contain the exact addresses of each pharmacy in the discount drug network search result. This information will be used to retrieve the exact lang/lat coordinates for the pharmacy markers on the map.
<div class="location d-none"><?php echo $pharmacy["pharmacy_address"] . ", " . $pharmacy["pharmacy_city"] ;?></div>
Now we are ready the code the script for our interactive map. The main elements of the code is explained in the script comments.
// you want to get it of the window global
const provider = new GeoSearch.OpenStreetMapProvider();
async function m(){
let prm = new Promise((resolve,reject) => {
//get the zip code submityted to the search form
let zip = document.getElementById("zip").innerText;
//Convert zip code into geo coordiates
resolve(provider.search({ query: zip }));
});
let res = await prm;
console.log(res[0].x);
//Set the View for the map
let mymap = L.map('mapid').setView([res[0].y, res[0].x], 11);
L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', {
attribution: 'Map data © <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
maxZoom: 18,
id: 'mapbox/streets-v11',
tileSize: 512,
zoomOffset: -1,
accessToken: 'pk.eyJ1IjoiaS1sb3ZlLWNvZGUtODQiLCJhIjoiY2tnbmd2aWJ6MDZyYjJ3bW94N2x2cjJmcyJ9.gh4aA_krzQdt3X7WQMMSQw'
}).addTo(mymap);
// for the markers on the map
async function f(){
//All Elements containing the precise addresses of the pharmacies contained in the search results
let location = document.getElementsByClassName("location");
let locationArr = [];
let result = [];
let marker = [];
// loop trough all of the divs (siblings) with the classname "location"
for (i = 0; i < location.length; i++){
//Create an Array containing all the precise pharmacy addresses from the search results
locationArr[i] = location[i].innerText;
let promise = new Promise((resolve, reject) => {
//Convert pharmacy adresses in geocoordionates
resolve(provider.search({ query: locationArr[i] }));
});
//Create an Array containing all the converted geocoordinates
result[i] = await promise;
// Set the markers on the map
if(result[i][0] !== undefined){
marker[i] = L.marker([result[i][0].y, result[i][0].x]).addTo(mymap);
}
/*console.log(result);*/
}
/*console.log(result);*/
// "done"
}
f();
}
m();