Sunday, 2 February 2014

Searching a leaflet.js map using the OSMGeocoder plugin


The following post is a portion of the Leaflet Tips and Tricks book which is free to download. To use this post in context, consider it with the others in this blog or just download the the book as a pdf / epub or mobi .
----------------------------------------------------------
OSMGeocoder Search
The OSMGeocoder plugin adds a search facility to a leaflet map that uses the OpenStreetMap tool ‘Nominatim’ to search for a location and provide a reverse geolocation on the search term to pinpoint the position on the map.
The plugin was developed by ‘kartenkarsten’ and is hosted on GitHub where it can be downloaded from.
There are a number of configurable options which we shall describe in a moment.

OSMGeocoder code description

The following code is a ‘bare bones’ listing which we will flesh out with some options. The version with the added options will be in the appendices and there will be a link to a live version on bl.ocks.org.
<!DOCTYPE html>
<html>
<head>
    <title>osmGeocoder Search Plugin for Leaflet Map</title>
    <meta charset="utf-8" />
    <link 
        rel="stylesheet" 
        href="http://cdn.leafletjs.com/leaflet-0.7/leaflet.css"
    />
    <link 
        rel="stylesheet" 
        href="http://k4r573n.github.io/leaflet-control-osm-geocoder/Control.OSMGeocoder.css"
    />
        
</head>
<body>
    <div id="map" style="width: 600px; height: 400px"></div>

    <script
        src="http://cdn.leafletjs.com/leaflet-0.7/leaflet.js">
    </script>
    <script
        src="http://k4r573n.github.io/leaflet-control-osm-geocoder/Control.OSMGeocoder.js">
    </script>
    
    <script>
        var map = L.map('map').setView([-41.2858, 174.78682], 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);
        
    </script>
</body>
</html>
There are only three ‘blocks’ that have changed in the code from our simple map example.
The first is an additional link to load more CSS code;
<link 
    rel="stylesheet" 
    href="http://k4r573n.github.io/leaflet-control-osm-geocoder/Control.OSMGeocoder.css"
/>
(Because of the length of the URL for the file, the formatting may make cutting and pasting from the ebook problematic. For a more reliable snippet of code, download the live version from GitHub)
This loads the file directly from the OSMGeocoder repository on GitHub, so if you are loading from a local file you will need to adjust the path appropriately.
The second is the block that loads the Control.OSMGeocoder.js script.
<script
    src="http://k4r573n.github.io/leaflet-control-osm-geocoder/Control.OSMGeocoder.js">
</script>
(Again because of the length of the URL for the file, the formatting may make cutting and pasting from the ebook problematic. For a more reliable snippet of code, download the live version from GitHub).
Control.OSMGeocoder.js exists as a separate block of JavaScript code and again, here we are loading the file directly from the OSMGeocoder repository on GitHub (as per the earlier advice, if you are loading from a local file you will need to adjust the path appropriately).
The last change to the file is the block of code that runs and configures Leaflet.draw.
        var osmGeocoder = new L.Control.OSMGeocoder();

        map.addControl(osmGeocoder);
The fist line (var osmGeocoder = new L.Control.OSMGeocoder();) initializes the osmGeocoder control and the second (map.addControl(osmGeocoder);) adds the search controls to the map.
There is not a lot of additional code required to get this plugin up and running and the following is what we see on the screen;
OSMGeocoder plugin
The only noticeable addition is a svelte magnifying glass in the top left hand corner. If we hover our mouse over the magnifying glass a search box appears.
OSMGeocoder plugin
If we then type in an address and click on ‘locate’…
OSMGeocoder plugin
… we are taken to a view of the location of our search.
OSMGeocoder plugin

OSMGeocoder configuration options

As I mentioned earlier, the sample code described above is in it’s most basic form and it can be extended using a range of options available to OSMGeocoder.
Adding in options is a simple matter of declaring them when we initialize the OSMGeocoder control. The three options we are going to introduce (there are more, but I’m opting for the simple ones) are to leave the search box up on the screen (no need to hover over the magnifying glass), we will position the search box in the bottom right corner (I’m not advocating this, it’s just for the sake of demonstration) and we will change the text for the button to ‘Find!’. The following are the options added to the OSMGeocoder control that will accomplish this;
        var osmGeocoder = new L.Control.OSMGeocoder({
            collapsed: false,
            position: 'bottomright',
            text: 'Find!',
   });
Resulting in a map that looks a little like this…
OSMGeocoder plugin
A copy of this file and all the files that appear in the book can be downloaded (in a zip file) when you download the book from Leanpub


The description above (and heaps of other stuff) is in the Leaflet Tips and Tricks book that can be downloaded for free (or donate if you really want to :-)).

9 comments:

  1. I'm starting to think you are from Wellington? Is this true?

    ReplyDelete
    Replies
    1. LOL! I'm afraid not, I just thought the geography of the area made for a pleasant looking map. Wellington has a great combination of roading, rail, buildings, water / land / hills. All the cool things that make for a good map IMHO.

      Delete
  2. This is where I live and was utterly surprised when you started having leaflet blog posts about it. Almost like you have catered them for me. I do enjoy your posts keep it up. Don't worry I will still read them if you choose somewhere else.

    ReplyDelete
    Replies
    1. Awesome! This would have to be a level of personalization that other blogs should aspire to! :-)
      I have a few more scheduled over the next couple of weeks, but they're coming directly from the book Leaflet Tips and Tricks (https://leanpub.com/leaflet-tips-and-tricks). If you don't have a copy, you should grab one since it includes all the leaflet.js info that's on the blog and a bit more (and the price is right).
      I'm certainly not thinking of shifting the area for mapping examples (Although I did consider the usual suspects like New York, London, Paris, Ashburton)
      Glad to hear that you're finding the information useful.

      Delete
    2. Well and truly useful, and in this case personalised. Looking to get into this more when I complete my postgraduate GIS study here in Wellington. Ashburton a usual suspect? Hilarious! Keep up the good work!

      Delete
  3. I have a silly question probably. I am trying to use this geocoder with my leaflet OSM map. After referencing the css and js files in my html and adding the variable for the geocoder and adding it to the map, I see the search lens in the top right corner of my map but when I search something nothing happens. My html is stored locally on my hard disk and the geocoder is being referenced directly from github. Does geocoding not work when the html is stored locally? This is my first webmap so I am just trying things on a local html file.

    ReplyDelete
    Replies
    1. It should work without problem. I make the assumption that you have a web server set up on your local machine? If not you will need one. Other than that I'm not sure what the problem might be. Sorry, I'm at a loss!

      Delete
    2. I'm very new to web programming so not aware of all the basic nuts and bolts of it. I realize now that I don't have a web server setup. That's kind of stupid I guess. I'll do it now using WampServer. Thank you for your above post, it was quite helpful to me.

      Delete
    3. Don't be too hard on yourself. Learning is the important part. Enjoy Leaflet!

      Delete