Create a gist now

Instantly share code, notes, and snippets.

Import JSON Data from an External File in Leaflet
<!DOCTYPE html>
<meta charset="utf-8">
<html>
<head>
<title>Cities I've Been To</title>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.6.4/leaflet.css" />
<!--[if lte IE 8]>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.6.4/leaflet.ie.css" />
<![endif]-->
<script src="http://cdn.leafletjs.com/leaflet-0.6.4/leaflet.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<style type="text/css">
#map {
height: 500px;
}
</style>
</head>
<body>
<h1></h1>
<div id="map"></div>
<script type="text/javascript">
var visitedIcon = L.icon({
iconUrl: 'visited.png',
iconSize: [32, 37],
shadowSize: [0, 0],
iconAnchor: [16, 37],
shadowAnchor: [0, 0],
popupAnchor: [0, -37]
});
var uncertainIcon = L.icon({
iconUrl: 'uncertain.png',
iconSize: [32, 37],
shadowSize: [0, 0],
iconAnchor: [16, 37],
shadowAnchor: [0, 0],
popupAnchor: [0, -37]
});
var map = L.map('map').setView([38.0740, -55], 3);
// map
function onEachFeature(feature, layer) {
layer.bindPopup(feature.properties.City + ", " + feature.properties.State + ", " + feature.properties.Country);
}
$.getJSON("cities.geoJSON", function (cities) { // pull data from external file
L.geoJson(cities, {
onEachFeature: onEachFeature,
pointToLayer: function (feature, latlng) {
switch (feature.properties.Remember) {
case '1': return L.marker(latlng, {icon: visitedIcon});
case '?': return L.marker(latlng, {icon: uncertainIcon});
case '0': return L.marker(latlng, {icon: uncertainIcon});
}
}
}).addTo(map);
})
L.tileLayer('http://tile.cloudmade.com/[api-key]/7/256/{z}/{x}/{y}.png', {
attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://cloudmade.com">CloudMade</a>',
maxZoom: 18
}).addTo(map);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment