wrld.js

Adding the Searchbar to a map

Add a searchbar to the map. This example creates markers for each search result and opens a popup when one is selected. To set up places on your map that can be searched, use the Places Designer with your API key.

This is an optional component with a few dependencies. To use it, you will have to include JQuery, wrld.css and searchbar.js as shown in the code sample below.

The searchbar can be used with the Marker Controller widget to more easily display markers for search results.

<!DOCTYPE HTML>
<html>
  <head>
    <script src="https://cdn-webgl.wrld3d.com/wrldjs/dist/latest/wrld.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.0.1/leaflet.css" rel="stylesheet" />

    <link href="https://cdn-webgl.wrld3d.com/wrldjs/addons/resources/latest/css/wrld.css" rel="stylesheet"/>
    <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
    <script src="https://cdn-webgl.wrld3d.com/wrldjs/addons/searchbar/latest/searchbar.js"></script>
  </head>
  
  <body>
  <div style="position: relative">
    <div id="widget-container" class="wrld-widget-container"></div>
    <div id="map" style="height: 400px"></div>
    <script>
      var map = L.Wrld.map("map", "your_api_key_here", {
        center: [37.79505, -122.40815],
        zoom: 15
      });

      var searchbarConfig = {
          apiKey: "your_api_key_here",
          outdoorSearchMenuItems: [
              {name: "Around Me", searchTag: "", iconKey: "aroundme"},
              {name: "Tourism", searchTag: "tourist_info", iconKey: "tourist_info"}
          ],
          locationJumps: [
              {name: "San Francisco", latLng: [37.7952, -122.4028]}
          ]
      };
      var searchbar = new WrldSearchbar("widget-container", map, searchbarConfig);
      searchbar.on("searchresultsclear", clearMarkers);
      searchbar.on("searchresultsupdate", addSearchResultMarkers);
      searchbar.on("searchresultselect", openSelectedResultPopup);

      var markers = [];

      function clearMarkers() {
          markers.forEach(function(marker) { marker.remove(); });
      }

      function addSearchResultMarkers(event) {
          clearMarkers();
          for (var poiId in event.results) {
              var result = event.results[poiId];
              var marker = L.marker(result.location.latLng, { title: result.title });
              marker.addTo(map);
              markers.push(marker);
          }
      }

      function openSelectedResultPopup(event) {
          map.openPopup(event.result.title, event.result.location.latLng);
      }
    </script>

  </div>
  </body>
</html>
v0.1.1452