In this post, I'll be showing you how to make a location picker in React with OpenStreetMap using the Niwa Location Picker library.
Setup the Project
First of all, set up the project. I'll be using vite to do this. Run this in your terminal.
npm create vite@latest
And create a new React project.
Installing Niwa Location Picker
Now you have to install niwa location picker because we will be using it to make our location picker.
npm i niwa-location-picker
Creating the location picker
Open the App.jsx file in your src folder. It should look like this.
import './App.css'
export default function App() {
return (
<main>
React ⚛️ + Vite ⚡ + Replit 🌀
</main>
)
}
Now add a state to keep track of the location that the user has selected.
const [location, setLocation] = useState([])
Add this markup to your App function.
<main>
<h2>Selected Location</h2>
<h3>Latitude: {location[0]}</h3>
<h3>Longitude: {location[1]}</h3>
<div id="map">
</div>
</main>
Now we'll use the useEffect hook to create a location picker using the niwa location picker at the time when the component is rendered.
useEffect(() => {
document.querySelector("#map").innerHTML = "";
const locationPicker = new LocationPicker('#map', {
height: 350,
countryCode: 910
});
locationPicker.addEventListener('MAP_CENTERED_ON_ADDRESS', (pos) => {
console.log('Lon Lat', pos.detail)
});
locationPicker.addEventListener('BROWSER_GEOLOCATED', (pos) => {
// console.log(pos)
let { latitude, longitude } = pos.detail.msg
// console.log(lat, lon)
locationPicker.removeAllMarkers()
locationPicker.addMarker(longitude, latitude, "#4444ff")
// form.setValues({
// position: [latitude, longitude],
// })
setLocation([latitude, longitude])
});
locationPicker.addEventListener('CLICKED_ON_LONLAT', (pos) => {
let { lat, lon } = pos.detail.coords
console.log(lat, lon)
locationPicker.removeAllMarkers()
locationPicker.addMarker(lon, lat, "#4444ff")
// form.setValues({
// position: [lat, lon],
// })
setLocation([lat, lon])
})
}, [])
Don't forget to import all of these and style.css from Niwa-location-picker
import './App.css'
import "niwa-location-picker/src/style.css"
import { LocationPicker } from "niwa-location-picker";
import { useEffect, useState } from 'react';
And add this code to App.css or wherever is your stylesheet file.
#map {
position: relative;
}
Done!
You can try it here on replit: https://replit.com/@AkshaySharma78/Location-Picker-using-Openlayers?v=1
GitHub repository: github.com/Akshay-Kumar-Sharma7807/Location..
Thanks for reading.