Created
February 2, 2017 02:00
-
-
Save rfriberg/6214dedce72ddb03e0fb81d9312825ca to your computer and use it in GitHub Desktop.
Country Finder | The mapzen.js geocoder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<title>Country Finder | The mapzen.js geocoder</title> | |
<meta charset="utf-8"> | |
<link rel="stylesheet" href="https://mapzen.com/js/mapzen.css"> | |
<script src="https://mapzen.com/js/mapzen.min.js"></script> | |
<style> | |
html,body{margin: 0; padding: 0} | |
#map { | |
height: 100%; | |
width: 100%; | |
position: absolute; | |
} | |
#title { | |
position: absolute; | |
z-index: 1000; | |
background: rgba(255, 255, 255, 0.85); | |
border-radius: 5px; | |
margin: 10px; | |
} | |
#country_name { | |
color: red; | |
font-family: "Helvetica Neue", Helvetica, sans-serif; | |
font-weight: normal; | |
margin: 10px; | |
} | |
#initial_text { | |
color: gray; | |
} | |
</style> | |
</head> | |
<body> | |
<div id="map"></div> | |
<div id="title"> | |
<h2 id="country_name"><div id="initial_text">Country Finder</div></h2> | |
</div> | |
<script> | |
// Mapzen API key (replace key with your own) | |
// To generate your own key, go to https://mapzen.com/developers/ | |
L.Mapzen.apiKey = 'mapzen-JA21Wes'; | |
var map = L.Mapzen.map('map', { | |
center: [37.632, -96.108], | |
zoom: 3 | |
}); | |
// Set up bounding box for highlighting | |
var bboxHighlighter = L.rectangle([[180, 90], [180, 90]], {color: 'red', weight: 3, fillOpacity: 0}).addTo(map); | |
// Define geocoder options | |
var geocoderOptions = { | |
position: 'topright', | |
layers: ['country'], | |
placeholder: 'Search for a country', | |
params: { | |
sources: ['wof'] | |
}, | |
place: true, | |
markers: false, | |
panToPoint: false | |
}; | |
// Instantiate the geocoder (a.k.a the search box) | |
var geocoder = L.Mapzen.geocoder(geocoderOptions); | |
// Add geocoder to map | |
geocoder.addTo(map); | |
// Add results listener | |
geocoder.on('results', function(e) { | |
// requestType may be 'autocomplete', 'search', or 'place' | |
if (e.requestType === 'place'){ | |
// Update country name in title | |
var name = e.results.features[0].properties.label; | |
document.getElementById('country_name').innerHTML = name; | |
// Get bounding box of result | |
var bbox = e.results.bbox; | |
var bounds = [ | |
[ bbox[1], bbox[0] ], | |
[ bbox[3], bbox[2] ] | |
]; | |
// Update bounds of bounding box | |
bboxHighlighter.setBounds(bounds); | |
// Zoom to bounding box | |
map.fitBounds(bounds); | |
} | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment