<commit_before>---
layout: tutorial
title: Using GeoJSON with Leaflet
---

<h3>Using GeoJSON with Leaflet</h3>

<p>GeoJSON is becoming a very popular data format among many GIS technologies and services — it's simple, lightweight, straightforward, and Leaflet is quite good at handling it. In this example, you'll learn how to create and interact with map vectors created from <a href="http://geojson.org/">GeoJSON</a> objects.</p>

<div id="map" style="height: 220px; margin-bottom: 18px"></div>

<script src="sample-geojson.js" type="text/javascript"></script>
<script>

	var map = L.map('map').setView([39.74739, -105], 13);

	L.tileLayer('http://{s}.tile.cloudmade.com/{key}/22677/256/{z}/{x}/{y}.png', {
		attribution: 'Map data &copy; 2011 OpenStreetMap contributors, Imagery &copy; 2011 CloudMade',
		key: '<KEY>'
	}).addTo(map);

	var baseballIcon = L.icon({
		iconUrl: 'baseball-marker.png',
		iconSize: [32, 37],
		iconAnchor: [16, 37],
		popupAnchor: [0, -28]
	});

	function onEachFeature(feature, layer) {
		var popupContent = "<p>I started out as a GeoJSON " +
				feature.geometry.type + ", but now I'm a Leaflet vector!</p>";

		if (feature.properties && feature.properties.popupContent) {
			popupContent += feature.properties.popupContent;
		}

		layer.bindPopup(popupContent);
	}

	L.geoJson({features: [freeBus, bicycleRental, campus]}, {

		style: function (feature) {
			return feature.properties && feature.properties.style;
		},

		onEachFeature: onEachFeature,

		pointToLayer: function (feature, latlng) {
			return L.circleMarker(latlng, {
				radius: 8,
				fillColor: "#ff7800",
				color: "#000",
				weight: 1,
				opacity: 1,
				fillOpacity: 0.8
			});
		}
	}).addTo(map);

	L.geoJson(coorsField, {

		pointToLayer: function (feature, latlng) {
			return L.marker(latlng, {icon: baseballIcon});
		},

		onEachFeature: onEachFeature
	}).addTo(map);

</script>

<p><a target="_blank" href="geojson-example.html">View example on a separate page &rarr;</a></p>

<h3>About GeoJSON</h3>

<p>According to <a href="http://geojson.org">http://geojson.org</a>:</p>

<blockquote>GeoJSON is a format for encoding a variety of geographic data structures. A GeoJSON object may represent a geometry, a feature, or a collection of features. GeoJSON supports the following geometry types: Point, LineString, Polygon, MultiPoint, MultiLineString, MultiPolygon, and GeometryCollection. Features in GeoJSON contain a geometry object and additional properties, and a feature collection represents a list of features.</blockquote>

<p>Leaflet supports all of the GeoJSON types above but <a href="http://geojson.org/geojson-spec.html#feature-objects">Features</a> and <a href="http://geojson.org/geojson-spec.html#feature-collection-objects">FeatureCollections</a> work best as they allow you to describe features with a set of properties. We can even use these properties to style our Leaflet vectors. (<a target="_blank" href="geojson-example.html">see example</a>)</p>

<h3>The GeoJSON layer</h3>

<p>GeoJSON objects are added to the map through a <a href="http://leaflet.cloudmade.com/reference.html#geojson">GeoJSON layer</a>. To create a GeoJSON layer and add it to a map we can use the following code.</p>

<pre><code class="css">var geojsonLayer = new L.GeoJSON();

map.addLayer(geojsonLayer);</code></pre>

<p>This creates an empty GeoJSON layer that we can easily add vectors to with the <code>addGeoJSON</code> method.</p>

<pre><code>var geojsonFeature = {
	"type": "Feature",
	"properties": {
		"name": "Coors Field",
		"amenity": "Baseball Stadium",
		"popupContent": "This is where the Rockies play!"
	},
	"geometry": {
		"type": "Point",
		"coordinates": [-104.99404, 39.75621]
	}
};

geojsonLayer.addGeoJSON(geojsonFeature);</code></pre>

<p>We can also instantiate the GeoJSON layer with a GeoJSON object to show it immediately, without having to call <code>addGeoJSON</code>.</p>

<pre><code>var geojsonLayer = new L.GeoJSON(geojsonFeature);

map.addLayer(geojsonLayer);</code></pre>

<h3>Popups</h3>

<p>We can use popups to show information about these features when they are clicked. To accomplish this we'll listen to the <code>featureparse</code> event of the GeoJSON layer. Here we're checking to see if a feature has a property named "popupContent" and if so binding a popup to the feature so this text (or HTML) appears when clicked.</p>

<pre><code>geojsonLayer.on("featureparse", function (e) {
	if (e.properties &amp;&amp; e.properties.popupContent){
		e.layer.bindPopup(e.properties.popupContent);
	}
});</code></pre>

<p>Make sure to do this <em>before</em> adding GeoJSON objects through the <code>addGeoJSON</code> method.</p>

<h3>Styling Features</h3>

<p>We can also listen to the <code>featureparse</code> event to style our Polyline and Polygon features. As with our popup content, we can store our styling information in the properties of the GeoJSON object as well. These style properties should match those found in <a href="http://leaflet.cloudmade.com/reference.html#path-options">path options</a>. Our feature with styling information might look something like:</p>

<pre><code>var freeBus = {
	"type": "Feature",
	"geometry": {
		"type": "LineString",
		"coordinates": [
			[-104.98726, 39.74136],
			[-104.98720, 39.74132],
			[-104.98715, 39.74127],
			[-104.98713, 39.74117],
			[-104.98712, 39.74106], ...
		]
	},
	"properties": {
		"name": "16th Street Free Bus",
		"style": {
			"color": "#004070",
			"weight": 4,
			"opacity": 0.9
		},
		"popupContent": "This is the 16th street free bus ..."
	}
};</code></pre>

<p>To change the feature's style from the Leaflet default, we simply call the <code>setStyle</code> method on our layer (<code>e.layer</code>) in our <code>featureparse</code> event listener.</p>

<pre><code>geojsonLayer.on("featureparse", function (e){
	if (e.properties &amp;&amp; e.properties.style &amp;&amp; e.layer.setStyle){
		// The setStyle method isn't available for Points. More on that below ...
		e.layer.setStyle(e.properties.style);
	}
});</code></pre>

<h3>Styling Points</h3>

<p>Points are handled differently than polylines and polygons. By default simple markers are drawn for GeoJSON Points. We can alter this by passing a <code>pointToLayer</code> function in a <a href="http://leaflet.cloudmade.com/reference.html#geojson-options">GeoJSON options</a> object when creating the GeoJSON layer. This function is passed a <a href="http://leaflet.cloudmade.com/reference.html#latlng">LatLng</a> and should return an instance of ILayer, in this case likely a <a href="http://leaflet.cloudmade.com/reference.html#marker">Marker</a> or <a href="http://leaflet.cloudmade.com/reference.html#circlemarker">CircleMarker</a>.</p>

<p>Here we're using a CircleMarker:</p>

<pre><code>var geojsonMarkerOptions = {
	radius: 8,
	fillColor: "#ff7800",
	color: "#000",
	weight: 1,
	opacity: 1,
	fillOpacity: 0.8
};

var geojsonLayer = new L.GeoJSON(someGeojsonFeature, {
	pointToLayer: function (latlng) {
		return new L.CircleMarker(latlng, geojsonMarkerOptions);
	}
});</code></pre>

<p>And here's an example of using a custom Marker:</p>

<pre><code>var geojsonLayer = new L.GeoJSON(someGeojsonFeature, {
	pointToLayer: function (latlng) {
		return new L.Marker(latlng, {
			icon: new MyCustomIcon()
		});
	}
});</code></pre>

<p>View the <a href="geojson-example.html">example page</a> to see in detail what is possible with the GeoJSON layer.</p>
<commit_msg>Don't show bus route segments under construction.<commit_after>---
layout: tutorial
title: Using GeoJSON with Leaflet
---

<h3>Using GeoJSON with Leaflet</h3>

<p>GeoJSON is becoming a very popular data format among many GIS technologies and services — it's simple, lightweight, straightforward, and Leaflet is quite good at handling it. In this example, you'll learn how to create and interact with map vectors created from <a href="http://geojson.org/">GeoJSON</a> objects.</p>

<div id="map" style="height: 220px; margin-bottom: 18px"></div>

<script src="sample-geojson.js" type="text/javascript"></script>
<script>

	var map = L.map('map').setView([39.74739, -105], 13);

	L.tileLayer('http://{s}.tile.cloudmade.com/{key}/22677/256/{z}/{x}/{y}.png', {
		attribution: 'Map data &copy; 2011 OpenStreetMap contributors, Imagery &copy; 2011 CloudMade',
		key: '<KEY>'
	}).addTo(map);

	var baseballIcon = L.icon({
		iconUrl: 'baseball-marker.png',
		iconSize: [32, 37],
		iconAnchor: [16, 37],
		popupAnchor: [0, -28]
	});

	function onEachFeature(feature, layer) {
		var popupContent = "<p>I started out as a GeoJSON " +
				feature.geometry.type + ", but now I'm a Leaflet vector!</p>";

		if (feature.properties && feature.properties.popupContent) {
			popupContent += feature.properties.popupContent;
		}

		layer.bindPopup(popupContent);
	}

	L.geoJson({features: [freeBus, bicycleRental, campus]}, {

		style: function (feature) {
			return feature.properties && feature.properties.style;
		},

		onEachFeature: onEachFeature,

		filter: function (feature, layer) {
			if (feature.properties) {
				// If the property "underConstruction" exists and is true, return false (don't render features under construction)
				return feature.properties.underConstruction !== undefined ? !feature.properties.underConstruction : true;
			} else {
				return true;
			}
		},

		pointToLayer: function (feature, latlng) {
			return L.circleMarker(latlng, {
				radius: 8,
				fillColor: "#ff7800",
				color: "#000",
				weight: 1,
				opacity: 1,
				fillOpacity: 0.8
			});
		}
	}).addTo(map);

	L.geoJson(coorsField, {

		pointToLayer: function (feature, latlng) {
			return L.marker(latlng, {icon: baseballIcon});
		},

		onEachFeature: onEachFeature
	}).addTo(map);

</script>

<p><a target="_blank" href="geojson-example.html">View example on a separate page &rarr;</a></p>

<h3>About GeoJSON</h3>

<p>According to <a href="http://geojson.org">http://geojson.org</a>:</p>

<blockquote>GeoJSON is a format for encoding a variety of geographic data structures. A GeoJSON object may represent a geometry, a feature, or a collection of features. GeoJSON supports the following geometry types: Point, LineString, Polygon, MultiPoint, MultiLineString, MultiPolygon, and GeometryCollection. Features in GeoJSON contain a geometry object and additional properties, and a feature collection represents a list of features.</blockquote>

<p>Leaflet supports all of the GeoJSON types above but <a href="http://geojson.org/geojson-spec.html#feature-objects">Features</a> and <a href="http://geojson.org/geojson-spec.html#feature-collection-objects">FeatureCollections</a> work best as they allow you to describe features with a set of properties. We can even use these properties to style our Leaflet vectors. (<a target="_blank" href="geojson-example.html">see example</a>)</p>

<h3>The GeoJSON layer</h3>

<p>GeoJSON objects are added to the map through a <a href="http://leaflet.cloudmade.com/reference.html#geojson">GeoJSON layer</a>. To create a GeoJSON layer and add it to a map we can use the following code.</p>

<pre><code class="css">var geojsonLayer = new L.GeoJSON();

map.addLayer(geojsonLayer);</code></pre>

<p>This creates an empty GeoJSON layer that we can easily add vectors to with the <code>addGeoJSON</code> method.</p>

<pre><code>var geojsonFeature = {
	"type": "Feature",
	"properties": {
		"name": "<NAME>",
		"amenity": "Baseball Stadium",
		"popupContent": "This is where the Rockies play!"
	},
	"geometry": {
		"type": "Point",
		"coordinates": [-104.99404, 39.75621]
	}
};

geojsonLayer.addGeoJSON(geojsonFeature);</code></pre>

<p>We can also instantiate the GeoJSON layer with a GeoJSON object to show it immediately, without having to call <code>addGeoJSON</code>.</p>

<pre><code>var geojsonLayer = new L.GeoJSON(geojsonFeature);

map.addLayer(geojsonLayer);</code></pre>

<h3>Popups</h3>

<p>We can use popups to show information about these features when they are clicked. To accomplish this we'll listen to the <code>featureparse</code> event of the GeoJSON layer. Here we're checking to see if a feature has a property named "popupContent" and if so binding a popup to the feature so this text (or HTML) appears when clicked.</p>

<pre><code>geojsonLayer.on("featureparse", function (e) {
	if (e.properties &amp;&amp; e.properties.popupContent){
		e.layer.bindPopup(e.properties.popupContent);
	}
});</code></pre>

<p>Make sure to do this <em>before</em> adding GeoJSON objects through the <code>addGeoJSON</code> method.</p>

<h3>Styling Features</h3>

<p>We can also listen to the <code>featureparse</code> event to style our Polyline and Polygon features. As with our popup content, we can store our styling information in the properties of the GeoJSON object as well. These style properties should match those found in <a href="http://leaflet.cloudmade.com/reference.html#path-options">path options</a>. Our feature with styling information might look something like:</p>

<pre><code>var freeBus = {
	"type": "Feature",
	"geometry": {
		"type": "LineString",
		"coordinates": [
			[-104.98726, 39.74136],
			[-104.98720, 39.74132],
			[-104.98715, 39.74127],
			[-104.98713, 39.74117],
			[-104.98712, 39.74106], ...
		]
	},
	"properties": {
		"name": "16th Street Free Bus",
		"style": {
			"color": "#004070",
			"weight": 4,
			"opacity": 0.9
		},
		"popupContent": "This is the 16th street free bus ..."
	}
};</code></pre>

<p>To change the feature's style from the Leaflet default, we simply call the <code>setStyle</code> method on our layer (<code>e.layer</code>) in our <code>featureparse</code> event listener.</p>

<pre><code>geojsonLayer.on("featureparse", function (e){
	if (e.properties &amp;&amp; e.properties.style &amp;&amp; e.layer.setStyle){
		// The setStyle method isn't available for Points. More on that below ...
		e.layer.setStyle(e.properties.style);
	}
});</code></pre>

<h3>Styling Points</h3>

<p>Points are handled differently than polylines and polygons. By default simple markers are drawn for GeoJSON Points. We can alter this by passing a <code>pointToLayer</code> function in a <a href="http://leaflet.cloudmade.com/reference.html#geojson-options">GeoJSON options</a> object when creating the GeoJSON layer. This function is passed a <a href="http://leaflet.cloudmade.com/reference.html#latlng">LatLng</a> and should return an instance of ILayer, in this case likely a <a href="http://leaflet.cloudmade.com/reference.html#marker">Marker</a> or <a href="http://leaflet.cloudmade.com/reference.html#circlemarker">CircleMarker</a>.</p>

<p>Here we're using a CircleMarker:</p>

<pre><code>var geojsonMarkerOptions = {
	radius: 8,
	fillColor: "#ff7800",
	color: "#000",
	weight: 1,
	opacity: 1,
	fillOpacity: 0.8
};

var geojsonLayer = new L.GeoJSON(someGeojsonFeature, {
	pointToLayer: function (latlng) {
		return new L.CircleMarker(latlng, geojsonMarkerOptions);
	}
});</code></pre>

<p>And here's an example of using a custom Marker:</p>

<pre><code>var geojsonLayer = new L.GeoJSON(someGeojsonFeature, {
	pointToLayer: function (latlng) {
		return new L.Marker(latlng, {
			icon: new MyCustomIcon()
		});
	}
});</code></pre>

<p>View the <a href="geojson-example.html">example page</a> to see in detail what is possible with the GeoJSON layer.</p>

{'fraction_non_alphanumeric': 0.14163364438195067, 'fraction_numerical': 0.02339256039882398, 'mean_word_length': 4.067033678756476, 'pattern_counts': {'":': 38, '<': 266, '<?xml version=': 0, '>': 266, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5409376', 'n_tokens_mistral': 5628, 'n_tokens_neox': 4925, 'n_words': 1528}