GeoJSON is not show up on top of leaflet map

35 Views Asked by At

I use Next.Js, react-leaflet and Targomo API to fetch polygon and I got multipolygon I tried to add this data in GesJSON to display it on top of leaflet. I am new for leaflet so I don´t know if I did something incorrect.

From code below, It was no error only no display GeoJSON on top of leaflet.

This is Geodata from fetching map api

{type: 'FeatureCollection', crs: {…}, features: Array(6), metadata: {…}}
crs
: 
properties
: 
{name: 'urn:ogc:def:crs:EPSG::3857'}
type
: 
"name"
[[Prototype]]
: 
Object
features
: 
Array(6)
0
: 
geometry
: 
coordinates
: 
Array(1)
0
: 
Array(1)
0
: 
Array(32884)
[0 … 9999]
[10000 … 19999]
[20000 … 29999]
[30000 … 32883]
length
: 
32884
[[Prototype]]
: 
Array(0)
length
: 
1
[[Prototype]]
: 
Array(0)
length
: 
1
[[Prototype]]
: 
Array(0)
type
: 
"MultiPolygon"
[[Prototype]]
: 
Object
id
: 
"fid-7906fbb8_18e12077f78_-6a65"
properties
: 
{time: 1800, area: 288562351.51640743}
type
: 
"Feature"
[[Prototype]]
: 
Object
1
: 
{type: 'Feature', geometry: {…}, properties: {…}, id: 'fid-7906fbb8_18e12077f78_-6a66'}
2
: 
{type: 'Feature', geometry: {…}, properties: {…}, id: 'fid-7906fbb8_18e12077f78_-6a67'}
3
: 
{type: 'Feature', geometry: {…}, properties: {…}, id: 'fid-7906fbb8_18e12077f78_-6a68'}
4
: 
{type: 'Feature', geometry: {…}, properties: {…}, id: 'fid-7906fbb8_18e12077f78_-6a69'}
5
: 
{type: 'Feature', geometry: {…}, properties: {…}, id: 'fid-7906fbb8_18e12077f78_-6a6a'}
length
: 
6
[[Prototype]]
: 
Array(0)
metadata
: 
{travelType: Array(4), travelEdgeWeights: Array(6), maxEdgeWeight: 1800, edgeWeight: 'time', transitMaxTransfers: Array(4), …}
type
: 
"FeatureCollection"
[[Prototype]]
: 
Object

This is my code.

"use client";
import React, { useState, useEffect } from "react";
import {  TargomoClient } from "@targomo/core";
import {
  MapContainer,
  Marker,
  Popup,
  GeoJSON, TileLayer
 
} from "react-leaflet";
import { defaultIcon } from "../../utils/icons/defaultIcon";
import { latLng } from "leaflet";



export const Map = () => {
  const [asyncPolygon, setAsyncPolygon] = useState({features:[]});

  useEffect(() => {
    const center: [number, number] = [60.36367102829055, 5.346489526985267]; // Coordinates to center the map
    const travelTimes: number[] = [300, 600, 900, 1200, 1500, 1800];
    const sources = [{ id: 0, lat: center[0], lng: center[1] }]; // // define the starting point
    const mode: string[] = ["walk", "bike", "transit", "car"];

    const options = {
      travelType: mode,
      travelEdgeWeights: travelTimes,
      maxEdgeWeight: 1800,
      edgeWeight: "time",
      transitMaxTransfers: mode.map((m) => (m === "transit" ? 5 : null)),
      serializer: "geojson",
    };

    const fetchData = async () => {
      const apiKey = process.env.NEXT_PUBLIC_TARGOMO_MAP_API_KEY;

      try {
        const client = new TargomoClient("westcentraleurope", `${apiKey}`);
        const polygons = await client.polygons.fetch(sources, options); // get the polygons
         console.log(polygons);
         setAsyncPolygon(polygons);

        // console.log(polygons.features.length>0 ?JSON.stringify(polygons.features):JSON.stringify(JSON));
        // const polygonsData = polygons.features.length>0 ?JSON.stringify(polygons.features):JSON.stringify(JSON);
      } catch (error) {
        console.error("Error fetching polygons:", error);
      }
    };

    fetchData();
  }, []);

  const position: [number, number] = [60.39299, 5.32415];

  return (
    <MapContainer
      center={position}
      zoom={15}
      scrollWheelZoom={false}
      style={{ height: "80vh", width: "100wh" }}
    
  
    >
      <TileLayer attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" />
      
      {/* <GeoJSON data={polygons} onEachFeature={onEachFeature} style={(feature)=>{fillColor:"red"}}/> */}
      {   asyncPolygon &&   <GeoJSON
          data={asyncPolygon}
          onEachFeature={(feature, layer) => {
            if (feature.geometry && feature.geometry.type === "MultiPolygon") {
                // Convert coordinates array to a string
                const coordinatesString = JSON.stringify(feature.geometry.coordinates);
                // Bind popup with coordinates string as content
                layer.bindPopup(coordinatesString);
            }
        
        }}
        style={() => ({
          fillColor: "red",
          color:"red",
          fillOpacity:1,
          zIndex: 33
        })}
      />}
     
    </MapContainer>
  );
};

export default Map;

0

There are 0 best solutions below