Skip to content

Instantly share code, notes, and snippets.

@ramiroaznar
Last active May 20, 2022 16:34
Show Gist options
  • Save ramiroaznar/516732febacb9be2ebf358dcde62c78a to your computer and use it in GitHub Desktop.
Save ramiroaznar/516732febacb9be2ebf358dcde62c78a to your computer and use it in GitHub Desktop.
Interaction and styling GeoJSON with Leaflet.js
<html>
<head>
<title>Interaction and styling GeoJSON with Leaflet.js</title>
<meta charset="utf-8">
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.css" />
<script src="http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.js"></script>
<style type="text/css">
html, body, #map{
height: 100%;
padding: 0;
margin: 0;
}
</style>
</head>
<body>
<div id="map"></map>
<script type="text/javascript">
var options = {
center: [0.5, 102],
zoom: 8
}
var geojson = [
{ "type": "FeatureCollection",
"features": [
{ "type": "Feature",
"geometry": {"type": "Point", "coordinates": [102.0, 0.5]},
"properties": {"prop0": "value0"}
},
{ "type": "Feature",
"geometry": {
"type": "LineString",
"coordinates": [
[102.0, 0.0], [103.0, 1.0], [104.0, 0.0], [105.0, 1.0]
]
},
"properties": {
"prop0": "value0",
"prop1": 0.0
}
},
{ "type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates": [
[ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0],
[100.0, 1.0], [100.0, 0.0] ]
]
},
"properties": {
"prop0": "value0",
"prop1": {"this": "that"}
}
}
]
}];
var map = L.map('map', options);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {attribution: 'OSM'})
.addTo(map);
var geoJsonLayer = L.geoJson(geojson, {style: styleFunction})
.addTo(map);
// function styleFunction(feature) {
// console.log(feature.geometry.type);
// switch (feature.geometry.type) {
// case 'LineString': return {color: "red"};
// case 'Polygon': return {color: "green"};
// }
// }
geoJsonLayer.on('mouseover', newStyle);
geoJsonLayer.on('mouseout', function(e) {
geoJsonLayer.resetStyle(e.target);
});
function newStyle(){
geoJsonLayer.setStyle({
color: "blue"
});
}
function styleFunction(){
return {color: "purple"};
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment