0

I have a React-leaflet map and I am looking to retrieve coordinates from my database (MongoDB) and I would like to render the results and add them to the map.

This is my React hook below, but I am having trouble with how to return the results and use a marker. At the moment, I am accessing the marker from a hard-coded JSON file and and I am looking to improve upon this.

import React, { useEffect } from "react";
import { Map as LeafletMap, TileLayer, Marker, Popup } from "react-leaflet";
import "./Map.css";
import { Link, MemoryRouter } from "react-router-dom";
import axios from "axios";
import * as cameraData from "./CameraCoords.JSON";

const Map = () => {
  const [setActiveCamera] = React.useState(null);
  const [setCoords] = React.useState([]);

  useEffect(() => {
    async function getCoords() {
      try {
        const res = await axios.get(
          "http://localhost:3000/api/mapCoordinates/mapCoordinates"
        );
        setCoords(res.data);
      } catch (error) {
        res.status(404).json({ noCoords: "No Coordinates Found" });
      }
    }
    getCoords();
  }, [setCoords]);

  return (
    <div style={{ margin: 100 }}>
      <h1>Camera Trap Map</h1>
      <LeafletMap
        center={[4.2105, 101.8758]}
        zoom={1}
        maxZoom={10}
        attributionControl={true}
        zoomControl={true}
        doubleClickZoom={true}
        scrollWheelZoom={true}
        dragging={true}
        animate={true}
        easeLinearity={0.35}
      >
        <TileLayer url="http://{s}.tile.osm.org/{z}/{x}/{y}.png" />
        {/* Tile layer needed to give attirbute to Map */}
        {cameraData.features.map(camera => (
          <Marker
            key={camera.properties.CAMERA_ID}
            position={[
              camera.geometry.coordinates[1],
              camera.geometry.coordinates[0]
            ]}
            onClick={() => {
              setActiveCamera(camera);
            }}
          >
            <Popup>
              <MemoryRouter initialEntries={["/"]}>
                <Link to="/imageGrid">Project 1</Link>
              </MemoryRouter>
            </Popup>
          </Marker>
        ))}
      </LeafletMap>
    </div>
  );
};

export default Map;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.