Moiz Ahmed
Moiz Ahmed

Reputation: 11

Isochrone Contours on a leaflet Map using Mapbox

I am trying get Isochrone contours when the user clicks on a Marker,

The official Mapbox Documentation uses the built in Mapbox JS methods but I can't make it work with Leaflet JS Here's what I have

function markerOnClick(lon, lat) {
  const urlBase = "https://api.mapbox.com/isochrone/v1/mapbox/";
  const profile = "cycling"; // Set the default routing profile
  const minutes = 10; // Set the default duration

  // Create a function that sets up the Isochrone API query then makes an fetch call
  async function getIso() {
    const query = await fetch(
      `${urlBase}${profile}/${lon},${lat}?contours_minutes=${minutes}&polygons=true&access_token=${accessToken}`,
      { method: "GET" }
    );
    const data = await query.json();
    map.getSource("iso").setData(data);
  }
  // From the official documentation

  map.addSource("iso", {
    type: "geojson",
    data: {
      type: "FeatureCollection",
      features: [],
    },
  });

  // I have tried to use the Leaflet geoJSON method to add it to the map
  L.geoJSON("iso", {
    type: "geojson",
    data: {
      type: "FeatureCollection",
      features: [],
    },
  }).addTo(map);

  // Can't find the substitute for this method in Leaflet
  map.addLayer(
    {
      id: "isoLayer",
      type: "fill",
      // Use "iso" as the data source for this layer
      source: "iso",
      layout: {},
      paint: {
        // The fill color for the layer is set to a light purple
        "fill-color": "#5a3fc0",
        "fill-opacity": 0.3,
      },
    },
    "poi-label"
  );

  // Make the API call
  getIso();
}

I have tried to use the Leaflet method of adding GeoJSON to the map i.e. L.geoJSON but to no avail the mapbox GL JS methods I am trying to replace are

  1. map.addLayer

  2. map.addSource

any advice would be appreciated

Upvotes: 0

Views: 245

Answers (1)

IvanSanchez
IvanSanchez

Reputation: 19069

L.geoJSON() expects a GeoJSON data structure, not a string. Do read https://leafletjs.com/reference#geojson .

For your particular case you probably want to do something like

const query = await fetch(`${urlBase}${profile}/${lon},${lat}?contours_minutes=${minutes}&polygons=true&access_token=${accessToken}`,{ method: "GET" });
const data = await query.json();
L.geoJson(data).addTo(map);

Upvotes: 1

Related Questions