Skip to content

Instantly share code, notes, and snippets.

@DevDhaif
Created March 7, 2022 01:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save DevDhaif/bfefe93891df0877d49c107d1456b225 to your computer and use it in GitHub Desktop.
Save DevDhaif/bfefe93891df0877d49c107d1456b225 to your computer and use it in GitHub Desktop.
Get geolocation (lat,lan) with leaflet ,reactjs
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='&copy; <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