Hello World

Map Search Geocoder with Mapzen Pelias

A geocoder is a utility that powers map search. It returns a set of Latitude and Longitude ("lat long") geocoordinates ("geocodes") when queried for an address (“814 Mission Street, San Francisco”), a landmark (“albert einstein statue”), a city/town/county ("Byron Bay"), and many businesses, services or attractions (“Hershey Chocolate World”). With geocode in hand, a marker or pin can be placed on the map at the desired location.

This Leaflet example demonstrates geocoding results from Mapzen’s Open Source Pelias project (more below), and it demonstrates reverse-geocoding, which simply finds and returns the nearest address to a lat long. In this example, you can move the marker and see the reverse geocoding result.

Our example also provides a helpful information box to display actual latitude and longitude, view bounds of the map corners, and zoom level.

We were recently introduced to the folks at Mapzen who have been doing amazing work with Open Source projects including geocoding, routing, and vector rendering. Their map search project is called "Pelias," and we’ve found it to be outstanding and a project we hope to contribute to.

Mapzen Search is free for up to 30,000 geocoding requests per day (and 6 per second). You can use the results to provide search results, and you can store a result for future reference (e.g., a lat long that maps your business). This is actually a great deal: most commercial geocoder providers won’t let you store a geocode without upgrading to a premium or top tier. If you believe your application will exceed Mapzen’s limits, just contact us and we’ll work with them to find a good solution.

Pelias is a separate service from MapJam, so you’ll have to get your own API key from MapZen here: Mapzen is awesome!


<!DOCTYPE html>
<html>
<head>
    
    <title>MapJam for Developers</title>
    <meta charset="utf-8">
    <meta name="ROBOTS" content="NOINDEX, NOFOLLOW">

    <!-- Add MapJam .js/.css and consolidated resources (Leaflet version 0 and MapboxGL libraries) -->
    <script src="https://res.mapjam.com/lib/0.9/mapjam.js"></script>
    <link href="https://res.mapjam.com/lib/0.9/mapjam.css" rel="stylesheet" />
    <script src="https://res.mapjam.com/lib/0.9/mapjam-resources-L0.js"></script>
    <link href="https://res.mapjam.com/lib/0.9/mapjam-resources-L0.css" rel="stylesheet" />

    <!-- Add jQuery -->
    <link href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
    <script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

    <!-- Mapzen libraries -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/leaflet-geocoder-mapzen/1.4.0/leaflet-geocoder-mapzen.css" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet-geocoder-mapzen/1.4.0/leaflet-geocoder-mapzen.js"></script>

    <style type='text/css'>

        /* add css for map */
        #mapDiv {
            position:absolute; top:0; bottom:0; width:100%;
        }

        body {
            margin:0; padding:0;
        }

        /* geocoder controls */
        .leaflet-control-container .leaflet-pelias-control{
          top:50px;
          left:300px !important;
        }

        /* address search box, input, typeahead results */
        #addressBox {
            position: absolute;
            top: 10px;
            left: 10px;
            width: 400px;
            height: 54px;
            padding: 5px 10px;
            color: white;
            background: rgba(0,0,0,0.5);
            font-size: 10pt;
            line-height: 26px;
            border-radius: 6px;
            text-align: left;
        }
        #tags {
            width: 394px;
            font-size: 10pt;
            color: #000;
        }
        .ui-widget {
            width: 390px;
            color: #000;
            font-size: 10pt;
        }
        
        /* various lat/lng display box*/
        #displayBox {
            position: absolute;
            bottom: 20px;
            right: 10px;
            padding: 5px 10px;  
            color: #fff;
            background: rgba(0,0,0,0.5);
            font-size: 10pt;
            line-height: 16px;
            height: 78px;
            border-radius:6px;
        }

    </style>

</head>

<body>

<!-- add div for map -->
<div id='mapDiv'></div>

<!-- add div for display of geocoordinates -->
<div id='displayBox'></div>

<!-- add div for address input -->
<div id='addressBox' class="ui-widget">
    <label for="tags">Input address to search. Move marker. Pan map.</label>
    <input id="tags">
</div>

<script>

    //** add MapJam map
    var map = new MJ.map('mapDiv', {
        centerMap: [-27.477336, 153.029859],
        zoom: 16,
        accessToken: 'insert-auth-token-here',
        markers:[]
    });


    //** add MapJam Marker
    var myMarker = new MJ.marker(map, {
        latLng: [-27.477336, 153.029859],
        draggable:true
    }).addTo(map);

    displayLatLng(map.getCenter().lat, map.getCenter().lng);


    //** move event is a zoom in/out or map pan
    map.on('moveend', function() {
        displayLatLng(myMarker.getLatLng().lat, myMarker.getLatLng().lng);
    });

    
    
    //** !!! get your Mapzen search api key at http://mapzen.com/developers !!!
      
    //** marker move - reverse geocode to find closest address at marker
    myMarker.on('dragend', function(e) {
        displayLatLng(e.target._latlng.lat, e.target._latlng.lng);
        $.ajax({
            url: "https://search.mapzen.com/v1/reverse",
            data: {'api_key': 'insert-mapzen-search-auth-token-here','point.lat':e.target._latlng.lat, 'point.lon':e.target._latlng.lng, 'layers':'address'},
            success: function(data) {
                $("#tags").val(data.features[0].properties.label);
            },
            cache: false
        });
    });

    
    //** Address input, suggestions and geocoding functions
    $("#tags").autocomplete({
        autoFocus: true,
        source: function (request, response) {        
            jQuery.get("https://search.mapzen.com/v1/autocomplete", {
                'api_key':'insert-mapzen-search-auth-token-here',
                'text':request.term              
            }, function (data) {
                var result =[];
                for (var i=0; i< data.features.length; i++){
                    result.push(data.features[i].properties.label);
                }
                response(result);
        });
    },
    select: function(event, ui) {
        var searchText = '';

        if(event.keyCode == 13) {
          if($("#tags").val().length==0) {
              event.preventDefault();
              return false;
          }else{
            searchText = $("#tags").val();
          }
        }else{
          searchText = ui.item.value;
        }

        $.ajax({
          url: "https://search.mapzen.com/v1/search",
          data: {'api_key': 'insert-mapzen-search-auth-token-here','text':searchText},
          success: function(data){
              var newLatLng = new L.LatLng(data.features[0].geometry.coordinates[1], data.features[0].geometry.coordinates[0]);
              $("#tags").val(data.features[0].properties.label).autocomplete('close');
              map.setView(newLatLng);
              myMarker.setLatLng(newLatLng);                
              displayLatLng(newLatLng.lat, newLatLng.lng);
          },
          cache: false
        });

        event.preventDefault();
        return false;
      }
    }).keydown(function(event){      
      if(event.keyCode == 13) {
        if(!$("#tags").val().length==0) {
            var searchText = $("#tags").val();

            $.ajax({
              url: "https://search.mapzen.com/v1/search",
              data: {'api_key': 'insert-mapzen-search-auth-token-here','text':searchText},
              success: function(data){
                  var newLatLng = new L.LatLng(data.features[0].geometry.coordinates[1], data.features[0].geometry.coordinates[0]);
                  $("#tags").val(data.features[0].properties.label).autocomplete('close');
                  map.setView(newLatLng);
                  myMarker.setLatLng(newLatLng);                
                  displayLatLng(newLatLng.lat, newLatLng.lng);
                  event.preventDefault();
                  return false;
              },
              cache: false
            });
        }
      }
    });


    //** Display marker lat/lng and map boundaries
    function displayLatLng(lat, lng) {
        var latLngCenter = map.getCenter();
        var latLngNE = map.getBounds().getNorthEast();
        var latLngSW = map.getBounds().getSouthWest();
        displayBox.innerHTML = 'Marker Lat/Lng: '+lat.toFixed(6)+', '+lng.toFixed(6)+'<br>'+
                               'Center Lat/Lng: '+latLngCenter.lat.toFixed(6)+', '+latLngCenter.lng.toFixed(6)+'<br>'+
                               'NE Bound Lat/Lng: '+latLngNE.lat.toFixed(6)+', '+latLngNE.lng.toFixed(6)+'<br>'+
                               'SW Bound Lat/Lng: '+latLngSW.lat.toFixed(6)+', '+latLngSW.lng.toFixed(6)+'<br>'+
                               'Zoom: '+map.getZoom();
    }




</script>
</body>

</html>