Skip to content

Instantly share code, notes, and snippets.

@mollietaylor
Created November 21, 2013 14:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save mollietaylor/7582459 to your computer and use it in GitHub Desktop.
Save mollietaylor/7582459 to your computer and use it in GitHub Desktop.
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>
@hannerr
Copy link

hannerr commented Aug 9, 2023

Hi Mollie, I just found your example and i find it very helpful, but one question please:
what would the cities.geoJSON File look like in this example?
I tried:
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [125.6, 10.1]
},
"properties": {
"city": "Dinagat Islands",
"state": "Dinagat Islands",
"country": "Dinagat Islands"
}
}
in cities.geojson, but I get an error...
I only used data from the file directly until now.
thanks hanna

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment