Crafting Unique and Customizeable Websites is my Passion

Crafting Unique and Customizeable Websites is my Passion

hero frame
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="" integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A==" crossorigin=""/>
<link rel="stylesheet" href=""/>

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="" integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA==" crossorigin=""></script>
<!-- Make sure you put this AFtER leaflet.js, when using with leaflet -->
<script src=""></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.


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"]?>,

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({ query:  zip }));
        let res = await prm;
        //Set the View for the map
        let mymap ='mapid').setView([res[0].y, res[0].x], 11);

        L.tileLayer('{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', {
        attribution: 'Map data &copy; <a href="">OpenStreetMap</a> contributors, <a href="">CC-BY-SA</a>, Imagery © <a href="">Mapbox</a>',
        maxZoom: 18,
        id: 'mapbox/streets-v11',
        tileSize: 512,
        zoomOffset: -1,
        accessToken: 'pk.eyJ1IjoiaS1sb3ZlLWNvZGUtODQiLCJhIjoiY2tnbmd2aWJ6MDZyYjJ3bW94N2x2cjJmcyJ9.gh4aA_krzQdt3X7WQMMSQw'

    // 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({ 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);
     // "done"



be the first to share shared this post

Leave a Reply

Your email address will not be published. Required fields are marked *

top frame
freebie picture

Sign up to my mailing list and receive occasional updates, new bogposts, freebies, giveaways and more

    Terms of privacy and data protection

    Get in Touch

    Feel free to send me a message. I'll gladly respond to all your requests.