Last active
September 6, 2019 17:57
-
-
Save SebastianHGonzalez/341feb9a1b5414f8b33fd1cf5983486b to your computer and use it in GitHub Desktop.
This file contains hidden or 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 React, { | |
useMemo, | |
useState, | |
useEffect, | |
useRef, | |
useCallback | |
} from "react"; | |
import { number } from "prop-types"; | |
import { Map, TileLayer, Marker } from "react-leaflet"; | |
import L from "leaflet"; | |
export default function LeafletExample({ lat, lng }) { | |
const [centerLat, setCenterLat] = useState(lat); | |
const [centerLng, setCenterLng] = useState(lng); | |
useEffect(() => { | |
if (Number.isFinite(lat)) { | |
setCenterLat(+lat); | |
} | |
}, [lat]); | |
useEffect(() => { | |
if (Number.isFinite(lng)) { | |
setCenterLng(+lng); | |
} | |
}, [lng]); | |
const [markerLat, setMarkerLat] = useState(lat); | |
const [markerLng, setMarkerLng] = useState(lng); | |
useEffect(() => { | |
if (Number.isFinite(lat)) { | |
setMarkerLat(+lat); | |
} | |
}, [lat]); | |
useEffect(() => { | |
if (Number.isFinite(lng)) { | |
setMarkerLng(+lng); | |
} | |
}, [lng]); | |
const [zoom] = useState(15); | |
const center = useMemo(() => ({ lat: centerLat, lng: centerLng }), [ | |
centerLat, | |
centerLng | |
]); | |
const marker = useMemo(() => ({ lat: markerLat, lng: markerLng }), [ | |
markerLat, | |
markerLng | |
]); | |
const updateMarkerPosition = useCallback( | |
position => { | |
setMarkerLat(position.lat); | |
setMarkerLng(position.lng); | |
} | |
); | |
return ( | |
<Map center={center} zoom={zoom}> | |
<TileLayer url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" /> | |
<DraggableMarker | |
position={marker} | |
onPositionChange={updateMarkerPosition} | |
/> | |
</Map> | |
); | |
} | |
LeafletExample.propTypes = { | |
lat: number.isRequired, | |
lng: number.isRequired | |
}; | |
const scale = 0.65; | |
const pointerIcon = new L.Icon({ | |
iconUrl: "/static/map-brand-marker.svg", | |
iconRetinaUrl: "/static/map-brand-marker.svg", | |
iconAnchor: [25 * scale, 80 * scale], | |
iconSize: [50 * scale, 80 * scale] | |
}); | |
function DraggableMarker({ onPositionChange, ...props }) { | |
const markerRef = useRef(); | |
const onDragend = useCallback( | |
() => | |
markerRef.current && | |
onPositionChange(markerRef.current.leafletElement.getLatLng()) | |
); | |
return ( | |
<Marker | |
icon={pointerIcon} | |
draggable | |
onDragend={onDragend} | |
ref={markerRef} | |
{...props} | |
/> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment