Created
March 7, 2022 01:47
-
-
Save DevDhaif/bfefe93891df0877d49c107d1456b225 to your computer and use it in GitHub Desktop.
Get geolocation (lat,lan) with leaflet ,reactjs
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,Marker,Popup,TileLayer } from 'react-leaflet' | |
//Component | |
function CreateListing() { | |
//Default coordinates | |
const[formData,setFormData]=useState({ | |
latitude:15.508457, | |
longitude:32.522854 | |
}) | |
//destructuring variables from the object | |
const {latitude,longitude}=formData | |
const onMutate=(e)=>{ | |
//this will not work if you have more other object in your form | |
if(typeof e.latlng === "object"){ | |
setFormData((prev)=>({ | |
...prev, | |
latitude:e.latlng.lat, | |
longitude:e.latlng.lng, | |
}) | |
) | |
} | |
} | |
return ( | |
<div className='h-56 w-12/12'> | |
<MapContainer style={{height:'100%',width:'100%'}} | |
center={[latitude,longitude]} | |
zoom={8} | |
scrollWheelZoom={true}> | |
<TileLayer attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' | |
url='https://{s}.tile.openstreetmap.de/tiles/osmde/{z}/{x}/{y}.png'/> | |
<Marker draggable position={[latitude,longitude]} | |
eventHandlers={{ | |
//eventListner here trigring onMutate , you can change it to (click) or whatever works with you | |
mouseover: (e) => onMutate(e) | |
}}> | |
//you can get rid of this variable , even the Popup tag | |
<Popup >{Listing.location}</Popup> | |
</Marker> | |
</MapContainer> | |
</div> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment