SearchRoad: Leaflet Mobile and Plugins

      Comments Off on SearchRoad: Leaflet Mobile and Plugins

SearchRoad is a tiny app for highlighting the power of functionalities among the different Leaflet’s plugins.

searchroad

 

Leaflet is a library very flexible, written in Javascript with potentiality and feature which render a webmap really completed.

Within blog an introduction has been already dealt with, in which the basis for pubblishing a completed map and figure out the functionalitie were described. Check out Leaflet: a short introduction

The aim of SearchRoad is to undestand which is the code we wanto to use in order to properly display an our map in Leaflet, on mobile as well. This guidelines presents a simple app, named SearchRoad based on one of several plugins whose the community makes widely use in asssociation to base library  leaflet.js .

We start to make visible our map on own smartphone. A basemap has been used, already used into intro leaflet_basemap.html, that we rename index.html

We must only add the following code to HTML and CSS page. So in <head> section of index.html :

<meta name=“viewport” content=“width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no” />

We give a CSS style to it in order to be compatible for Chrome browser on mobile phone. Notice that the presence of vw instead of % because a bug on such browser.

    <style type=”text/css”>
html, body,#map {height: 100%;
width: 100vw;
}
    </style>

On adding only these few rows, the basemap is already visible on every kind device.

Once enabled the map, It is possible to visualize it on mobile’s browser.Now,  We add a functionality for making it iteractive. So, we get OSM Geocoder  plugin, developed for performing Openstreetmap Nominatim Geocoder APIs .

We add the following rows for inserting the plugin from CDN.

<script src=“https://rawgit.com/k4r573n/leaflet-control-osm-geocoder/master/Control.OSMGeocoder.js”></script>
<link rel=“stylesheet” href=“https://rawgit.com/k4r573n/leaflet-control-osm-geocoder/master/Control.OSMGeocoder.css” />

The base plugin works on adding in <script> section the two red row below, which recall the plugin library:

        var map = L.map('map').setView([48.854716, 2.349014 ], 14);
        mapLink = 
            '<a href="http://openstreetmap.org">OpenStreetMap</a>';
        L.tileLayer(
            'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '&copy; ' + mapLink + ' Contributors',
            maxZoom: 18,
            }).addTo(map);
                        
		var osmGeocoder = new L.Control.OSMGeocoder();

		map.addControl(osmGeocoder);

Visit the official demo to figure out its mode of operation.

As we can see, the map requires to search a place to user. Nominatim library researchs the address and as results it provides a bounding box, that is a zoom on the serched zone. And if we want to add also a marker which locates exactly the address? In order to answer to that question, we must use the options which plugin arranges for us, by modifying the callback function on clicking by mouse. Some code has been inserted for extracting the centre of bounding box, in way that it extrapolates lat and long of this point. Such couple of coordinates will be inserted into javascript object which identifies the marker. The marker is represented by an icon, upon declared

        var map = L.map('map').setView([48.854716, 2.349014 ], 14);
        mapLink = 
            '<a href="http://openstreetmap.org">OpenStreetMap</a>';
        L.tileLayer(
            'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '&copy; ' + mapLink + ' Contributors',
            maxZoom: 18,
            }).addTo(map);
            
            //Qui dichiariamo le opzioni del'oggetto javascript rappresentante il Geocoder
            var options = {
                   collapsed: false, /* Whether its collapsed or not */
                   position: 'topright', /* The position of the control */
                   text: 'Search', /* The text of the submit button */
                   placeholder: 'Search location', /* The text of the search input placeholder */
                   callback: function (results) {
		               	var bbox = results[0].boundingbox;
				        first = new L.LatLng(bbox[0], bbox[2]);           /* Qui cerchiamo il centro della mappa per passare*/
				        second = new L.LatLng(bbox[1], bbox[3]);          /* le lat e long al marker */ 
				        bounds = new L.LatLngBounds([first, second]);
				        var center= bounds.getCenter();         /*utiliziamo il metodo getCenter()  per estrarre il centro della Bounding box*/
			            this._map.fitBounds(bounds);

		              //creiamo la variabile icona
                         var myIcon = L.icon({
					     iconUrl: 'https://raw.githubusercontent.com/k4r573n/leaflet-control-osm-geocoder/master/demo/images/marker-icon.png',
                          });
                      // creiamo il marker
                         var marker = L.marker(center, {
                                       icon: myIcon
                                         });        
                          marker.addTo(map)
		                  }
	                  };
            
		var osmGeocoder = new L.Control.OSMGeocoder(options);  //Qui passiamo la varibile option

		map.addControl(osmGeocoder);

SearchRoad is visible below. Note that the callback function inserts on the map a marker which locates the address with a satisfying precision.

                                                                               Allarga la mappa

Conclusion

SearchRoad highlights one of the multiple possibilities which LeafletJS provides to users, thanks to use of its plugins which widely simplify the scripting language for performing each kind of feature to a map. The exercise we have seen can be improved, Actually, we can enhanced the accuracy of the marker on the map. On the other hand,it is a little bit complicated to consider another type of feature as result. An example: in case we want to search a road or a square we would like to highlights them through a colored line or polygon.