Last active
May 14, 2023 18:17
-
-
Save Misfit-Ha/e204010c421e4d734c0cf5552d754cc7 to your computer and use it in GitHub Desktop.
Highlight every road inside an area using React-leaflet
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
import { MapContainer, Polyline, TileLayer } from 'react-leaflet' | |
import 'leaflet/dist/leaflet.css' | |
import 'leaflet-defaulticon-compatibility/dist/leaflet-defaulticon-compatibility.webpack.css' // Re-uses images from ~leaflet package | |
import { useState } from 'react' | |
export default function SimpleMap() { | |
const [roads, setRoads] = useState([]) | |
const clickHandler = async () => { | |
const requestOptions = { | |
method: 'GET', | |
redirect: 'follow', | |
} | |
try { | |
//fetch every road inside the predefined polygon, filter by roads where maxspeed is above 40 | |
const response = await fetch( | |
'https://overpass-api.de/api/interpreter?data=[out:json];way(poly:"28.995790454585077 50.82851415553776 28.9639072205959 50.81571487021483 28.945306891835415 50.83801486146277 28.954089911144663 50.85892332512779 28.96595467266438 50.85184681740384 28.97241758219053 50.86413328761432 28.997350420494854 50.832932823059764 28.995790454585077 50.82851415553776")["highway"]["maxspeed"~"^40$|^[4-9][0-9]$|^[1-9][0-9]{2,}$"];out geom;', | |
requestOptions | |
) | |
let result = await response.text() | |
console.log(result) | |
result = JSON.parse(result) | |
setRoads(result.elements) | |
} catch (error) { | |
console.log('error', error) | |
} | |
} | |
//style lines | |
const polylineOptions = { | |
weight: 5, | |
color: '#FF7A01', | |
dashArray: '25, 25', | |
opacity: 0.5, | |
} | |
return ( | |
<div> | |
<MapContainer | |
center={{ | |
lat: 28.9674, | |
lng: 50.8369, | |
}} | |
zoom={14} | |
scrollWheelZoom={true} | |
style={{ height: 400, width: '100%' }} | |
> | |
<TileLayer url='https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png' /> | |
{roads.length > 0 && roads.map((element, index) => ( | |
<Polyline | |
key={index} | |
positions={element.geometry.map((coord) => [coord.lat, coord.lon])} | |
pathOptions={polylineOptions} | |
/> | |
))} | |
</MapContainer> | |
<button onClick={clickHandler} > fetch </button> | |
</div> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment