Skip to content

Commit

Permalink
added layout map with marker address and radius
Browse files Browse the repository at this point in the history
  • Loading branch information
MathisZerbib committed Jun 4, 2024
1 parent aef2c42 commit 675b3ac
Show file tree
Hide file tree
Showing 2 changed files with 143 additions and 46 deletions.
152 changes: 133 additions & 19 deletions src/components/MapWithGeocoder.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,16 @@ import MapboxGeocoder from "@mapbox/mapbox-gl-geocoder";
import "mapbox-gl/dist/mapbox-gl.css";
import "@mapbox/mapbox-gl-geocoder/dist/mapbox-gl-geocoder.css";

// Assuming VITE_MAPBOX_ACCESS_TOKEN is correctly set in your environment variables
mapboxgl.accessToken = import.meta.env.VITE_MAPBOX_ACCESS_TOKEN;

interface MapWithGeocoderProps {
onSelectedAddress: (address: string) => void; // Define the prop type
onSelectedAddress: (address: string) => void;
}

const MapWithGeocoder: React.FC<MapWithGeocoderProps> = ({
onSelectedAddress,
}) => {
const mapRef = useRef<HTMLDivElement>(null);
const searchBarRef = useRef<HTMLInputElement>(null);
const [address, setAddress] = React.useState("");

useEffect(() => {
Expand All @@ -24,42 +22,158 @@ const MapWithGeocoder: React.FC<MapWithGeocoderProps> = ({
const map = new mapboxgl.Map({
container: mapRef.current,
style: "mapbox://styles/mapbox/streets-v12",
// Starting position in south of france montpellier
center: [3.8767, 43.6116], // Starting position [lng, lat]
zoom: 13, // Starting zoom
center: [3.8767, 43.6116],
zoom: 12,
});

const geocoder = new MapboxGeocoder({
accessToken: mapboxgl.accessToken,
mapboxgl: mapboxgl,
marker: false,
placeholder: "Chercher une adresse",
countries: "fr",
language: "fr",
addressAccuracy: "street",
types: "address,poi",
limit: 5,
});
map.addControl(geocoder);

const geocoderContainer = document.createElement("div");
geocoderContainer.className = "geocoder-container";
geocoderContainer.appendChild(geocoder.onAdd(map));

map.getContainer().appendChild(geocoderContainer);

map.addControl(
new mapboxgl.GeolocateControl({
positionOptions: {
enableHighAccuracy: true,
},
// When active the map will receive updates to the device's location as it changes.
trackUserLocation: true,
// Draw an arrow next to the location dot to indicate which direction the device is heading.
showUserHeading: true,
})
}),
"bottom-right"
);

geocoder.on("result", (result) => {
console.log("Selected address:", result.result.place_name);
setAddress(result.result.place_name);
onSelectedAddress(result.result.place_name); // Call the prop function with the selected address
const marker = new mapboxgl.Marker({
draggable: true,
color: "#00BF0A",
})
.setLngLat(map.getCenter())
.addTo(map);

const fetchAddress = (lngLat: mapboxgl.LngLat) => {
const url = `https://api.mapbox.com/geocoding/v5/mapbox.places/${lngLat.lng},${lngLat.lat}.json?access_token=${mapboxgl.accessToken}`;
fetch(url)
.then((response) => response.json())
.then((data) => {
if (data.features && data.features.length > 0) {
const place = data.features[0].place_name;
setAddress(place);
onSelectedAddress(place);
}
})
.catch((error) => console.error("Error fetching address:", error));
};

const addCircle = (lngLat: mapboxgl.LngLat) => {
const radiusInMeters = 1000;

const circleSource = map.getSource("circle") as mapboxgl.GeoJSONSource;
circleSource?.setData({
type: "Feature",
geometry: {
type: "Point",
coordinates: [lngLat.lng, lngLat.lat],
},
properties: {},
});

if (!map.getLayer("circle")) {
map.addLayer({
id: "circle",
type: "circle",
source: {
type: "geojson",
data: {
type: "Feature",
geometry: {
type: "Point",
coordinates: [lngLat.lng, lngLat.lat],
},
properties: {}, // Add an empty properties object
},
},
paint: {
"circle-radius": {
stops: [
[0, 0],
[20, radiusInMeters / 3],
],
base: 2,
},
"circle-color": "#0089BF",
"circle-opacity": 0.3,
"circle-stroke-width": 2,
"circle-stroke-color": "#00BF0A",
},
});
}
};

marker.on("drag", () => {
const lngLat = marker.getLngLat();
addCircle(lngLat);
});

marker.on("dragend", () => {
const lngLat = marker.getLngLat();
fetchAddress(lngLat);
addCircle(lngLat);
});

geocoder.on("result", (event) => {
const lngLat = event.result.geometry.coordinates;
marker.setLngLat(lngLat);
map.flyTo({ center: lngLat });
setAddress(event.result.place_name);
onSelectedAddress(event.result.place_name);
addCircle(marker.getLngLat());
});

map.on("click", (event: mapboxgl.MapMouseEvent) => {
const lngLat = event.lngLat;
marker.setLngLat(lngLat);
fetchAddress(lngLat);
addCircle(lngLat);
});

map.on("load", () => {
addCircle(map.getCenter());
});

return () => map.remove(); // Cleanup on unmount
}, [onSelectedAddress]); // Add onSelectedAddress as a dependency
return () => map.remove();
}, [onSelectedAddress]);

return (
<div>
<div ref={mapRef} style={{ width: "100%", height: "100vh" }}></div>
</div>
<>
<div ref={mapRef} style={{ width: "100%", height: "90vh" }}></div>
<style>
{`
.geocoder-container {
position: absolute;
top: 10px;
left: 50%;
transform: translateX(-50%);
width: 80%;
z-index: 1;
}
.mapboxgl-ctrl-geocoder {
min-width: 100%;
}
`}
</style>
</>
);
};

Expand Down
37 changes: 10 additions & 27 deletions src/pages/CheckoutPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,7 @@ function CheckoutPage({ open, onClose }: any) {
setOpenModal(false);
};

const handleOpenDrawer = () => {
setOpenDrawer(true);
};

const handleCloseDrawer = () => {
const handleCloseDrawerAddress = () => {
setOpenDrawer(false);
};

Expand Down Expand Up @@ -133,29 +129,16 @@ function CheckoutPage({ open, onClose }: any) {
<EmptyCart />
)}
{/* fees for the overall process of delivery */}
<p
{/* <p
style={{
alignSelf: "flex-end",
}}
>
{/* Frais de gestion: {fees.toFixed(4)} {selectedCurrency} */}
{/* //same here */}
{parseInt(totalPriceFeesIncluded) > 0
? `Frais de gestion: ${fees.toFixed(4)} ${selectedCurrency}`
: ""}
</p>
<h2
style={{
alignSelf: "flex-end",
}}
>
{
// do not show if the total price is 0
parseInt(totalPriceFeesIncluded) > 0
? `Total: ${totalPriceFeesIncluded} ${selectedCurrency}`
: ""
}
</h2>
</p> */}

<div style={{ marginTop: "20px", marginBottom: "20px" }}>
<BuyWithCrypto
enabled={
Expand All @@ -179,7 +162,9 @@ function CheckoutPage({ open, onClose }: any) {
}}
disabled={parseInt(totalPriceFeesIncluded) === 0} // Disable the button if the total is 0
>
{selectedAddress ? selectedAddress : "Selectionner votre adresse"}
{selectedAddress
? selectedAddress
: "Faites vous livrer en moins de 2H"}
<FontAwesomeIcon
icon={faPersonBiking}
style={{
Expand All @@ -192,7 +177,7 @@ function CheckoutPage({ open, onClose }: any) {
<SwipeableDrawer
anchor="bottom"
open={openDrawer}
onClose={handleCloseDrawer}
onClose={handleCloseDrawerAddress}
onOpen={() => {}}
>
<AppBar
Expand All @@ -205,7 +190,7 @@ function CheckoutPage({ open, onClose }: any) {
<IconButton
edge="start"
color="inherit"
onClick={handleCloseDrawer}
onClick={handleCloseDrawerAddress}
aria-label="close"
>
<FontAwesomeIcon icon={faClose} />
Expand Down Expand Up @@ -257,9 +242,7 @@ function CheckoutPage({ open, onClose }: any) {
marginRight: "auto",
}}
>
{selectedAddress
? selectedAddress
: "Selectionner votre adresse"}
{selectedAddress ? selectedAddress : "Adresse de livraison"}
</p>
</Toolbar>
</AppBar>
Expand Down

0 comments on commit 675b3ac

Please sign in to comment.