I am working in react js. I need to implement map using react-google-map with given features.
- On clicking "Zone" (say Zone 1 ) button map corresponding to zone should displayed ( Eg if you click zone 1 dispay map of zone and so on).
- Each zone there will be multiple polygons .We can edit polygon if required.
- We can create new map zone (empty map) by clicking 'Add zone' button
Given below is the code that I tried . I tried to edit the polygon cordinates and store them in local storage , but it is not updating properly and also I am not able new create empty map on clicking "Add zone" button. There will be locally saved polygons displayed in new map. I think idea is clear . Please do ask doubts is any.
Sample JSON format
{
"area": "Zone2",
"cartamount": "",
"extra_shippingamount": "",
"polygon": [
{
"id_polygon": 1,
"coord": [
{
"lat": 11.174036305817275,
"lng": 76.3754534171875
},
{
"lat": 10.526644973776667,
"lng": 76.6061663078125
},
{
"lat": 10.75339097376777,
"lng": 77.47957939375
}
]
},
{
"id_polygon": 2,
"coord": [
{
"lat": 11.28179683077826,
"lng": 75.89857811201172
},
{
"lat": 10.774977003245414,
"lng": 76.16774315107422
},
{
"lat": 11.292570666429365,
"lng": 76.91481346357422
}
]
}
],
"shippingamount": ""
},
{
"area": "Zone3",
"cartamount": "",
"extra_shippingamount": "",
"polygon": [
{
"id_polygon": 1,
"coord": [
{
"lat": 11.174036305817275,
"lng": 76.3754534171875
},
{
"lat": 10.526644973776667,
"lng": 76.6061663078125
},
{
"lat": 10.75339097376777,
"lng": 77.47957939375
}
]
},
{
"id_polygon": 2,
"coord": [
{
"lat": 11.28179683077826,
"lng": 75.89857811201172
},
{
"lat": 10.774977003245414,
"lng": 76.16774315107422
},
{
"lat": 11.292570666429365,
"lng": 76.91481346357422
}
]
}
],
"shippingamount": ""
}
]
Code
const MapContainer = withGoogleMap((props: any) => {
const { mainStore } = useStore();
const [curLocation, setCurLocation] = useState<any>()
const [loading, setLoading] = useState(true);
const [coordinates, setCoordinates] = useState<any>([]);
const [path, setPath] = useState<any>()
const polygonRef = useRef<any>(null);
const listenersRef = useRef([]);
let coord = coordIndex
let localCoordinates: any = [];
let getLocalCoordinates = localStorage.getItem("polygons");
if (typeof getLocalCoordinates == 'string') {
localCoordinates = JSON.parse(getLocalCoordinates);
}
console.log(" localCoordinates", localCoordinates)
useEffect(() => {
setLoading(true)
getGeoLocation()
}, [])
const getGeoLocation = () => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
position => {
// console.log(position.coords);
setCurLocation({ lat: position.coords.latitude, lng: position.coords.longitude })
})
setLoading(false)
}
else {
console.log("error")
// (err: any => console.log(error) ),
}
}
const getPaths = (polygon: any) => {
var polygonCount = localCoordinates.length == 0 ? 1 : localCoordinates.length + 1
var polygonBounds = polygon.getPath();
var bounds = [];
for (var i = 0; i < polygonBounds.length; i++) {
var point = {
lat: polygonBounds.getAt(i).lat(),
lng: polygonBounds.getAt(i).lng()
};
bounds.push(point);
}
localCoordinates?.push({
"id_polygon": polygonCount,
"coord": bounds
});
localStorage.setItem('polygons', JSON.stringify(localCoordinates))
console.log("bounds", bounds);
// mainStore.coorindates.push(bounds);
mainStore.isLatLng = true;
polygonCount++
}
console.log(" coordinates", coordinates)
const onEdit = useCallback((key: any) => {
console.log("polygonRef", polygonRef)
console.log("key", key)
if (polygonRef.current) {
const nextPath = polygonRef?.current
.getPath()
.getArray()
.map((latLng: any) => {
return { lat: latLng.lat(), lng: latLng.lng() };
});
console.log("nextPath", nextPath)
// setPath(nextPath);
}
}, [])
// Bind refs to current Polygon and listeners
const onLoad = useCallback(
polygon => {
polygonRef.current = polygon;
const path = polygon.getPath();
(listenersRef as any).current.push(
path.addListener("set_at", onEdit),
path.addListener("insert_at", onEdit),
path.addListener("remove_at", onEdit)
);
},
[onEdit]
);
return (
<div className="p-grid p-fluid">
<div className="p-col-12">
<div className="p-grid">
<div className="p-md-2">
</div>
{loading ? <div>Loading</div> :
curLocation?.lat && curLocation?.lng &&
<>
< GoogleMap
defaultZoom={8}
defaultCenter={{ lat: curLocation?.lat, lng: curLocation?.lng }}
>
{console.log("cooedIndex", path)}
{localCoordinates?.map((items: any, key: any) =>
<Polygon
key={items?.id_polygon}
editable
draggable
path={items.coord}
ref={polygonRef}
onMouseUp={() => onEdit(items.id_polygon)}
onDrag={() => onEdit(items.id_polygon)}
// onClick={(e: any) => console.log("polygon key", items.id_polygon)}
options={{
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.35,
geodesic: true,
editable: true
}}
/>
)}
<DrawingManager
defaultDrawingMode={google.maps.drawing.OverlayType.POLYGON}
defaultOptions={{
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: [google.maps.drawing.OverlayType.POLYGON]
},
polygonOptions: { editable: true, draggable: true }
}}
onPolygonComplete={value => getPaths(value)}
/>
<Marker position={{ lat: curLocation?.lat, lng: curLocation?.lng }} />
</GoogleMap>
<div>
</div>
</>
}
</div>
<div className="p-md-3">
</div>
</div>
</div >
)
})