import React, { useState, useEffect } from "react";
import ReactMapGl from "react-map-gl";
import mapboxgl from "mapbox-gl";
import LocationIcon from "./LocationIcon.svg";
const MapBox = () => {
const [location, setLocation] = useState({
lat: 28.6448,
long: 77.216,
zoom: 6,
});
useEffect(() => {
mapboxgl.accessToken =
"pk.eyJ1IjoiYmFidWppaHUiLCJhIjoiY2xtN29pMWQwMDBhdDNjcXFyZGl3dHI3diJ9.hWaEKZZWQa1yGxbT64SvOw";
const map = new mapboxgl.Map({
container: "map",
style: "mapbox://styles/mapbox/streets-v12",
center: [location.long, location.lat],
zoom: location.zoom,
});
map.on("moveend", () => {
const newLocation = {
lat: map.getCenter().lat.toFixed(4),
long: map.getCenter().lng.toFixed(4),
zoom: map.getZoom().toFixed(2),
};
console.log("Changed Location:", newLocation);
setLocation(newLocation);
});
return () => {
map.remove();
};
}, [location]);
return (
<div>
<div id="map" style={{ width: "100%", height: "400px" }}>
<ReactMapGl
{...location}
mapStyle="mapbox://styles/mapbox/streets-v12"
onViewportChange={(viewport) => setLocation(viewport)}
/>
</div>
<img
src={LocationIcon}
alt="Location Marker"
style={{
position: "absolute",
width: "30px",
height: "30px",
left: "50%",
top: "50%",
transform: "translate(-50%, -50%)",
}}
/>
<p>Latitude : {location?.lat}</p>
<p>Longitude : {location?.long}</p>
</div>
);
};
export default MapBox;