Hexycode
Hexycode

Reputation: 458

Displaying json data on leaflet map

I would like to create an web app which is going to show amount of available spots and bikes on a station.

I have an open API with is providing a real-time data. - API HERE

I'm using Leaflet Maps for map.

I currently have made 2 scripts.

leafletmap.js

This script is showing a map with center location of Oslo, Norway.

var mymap = L.map('mapid').setView([59.9139, 10.7522], 13); // This line is lan,lat for location, "13" is a zoom parameter.

    L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
        maxZoom: 18,
        attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, ' +
            '<a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
            'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
        id: 'mapbox/streets-v11',
        tileSize: 512,
        zoomOffset: -1
    }).addTo(mymap);

    

    L.circle([59.9139, 10.7522], 60, { // This is what I want to use as bike station 
location
        color: 'blue',
        fillColor: 'blue',
        fillOpacity: 0.5
    }).addTo(mymap).bindPopup("I am a circle.");

Here is a code for receiving data from API.

api.js

const GbfsClient = require('gbfs-client');
const gbfsClient = new GbfsClient('https://gbfs.urbansharing.com/oslobysykkel.no/');

gbfsClient.stationInfo()
    .then(osloStatus => console.log(osloStatus));

I want to display a Bike station locations on my map.

This end-point is the one that I need to use - https://gbfs.urbansharing.com/oslobysykkel.no/station_information.json

Goal: Change this hard-scripted part of the code >

L.circle([*lat and lon to be inserted here*], 60, {
        color: 'blue',
        fillColor: 'blue',
        fillOpacity: 0.5
    }).addTo(mymap).bindPopup("**Name of bike station here.**");

To be changed with a response of endpoint > Lat, lan, name of bike station.

JSON response >

{
  "last_updated": 1553592653,
  "data": {
    "stations": [
      {  
        "station_id":"627",
        "name":"Skøyen Stasjon",
        "address":"Skøyen Stasjon",
        "lat":59.9226729,
        "lon":10.6788129,
        "capacity":20
      },
      {  
        "station_id":"623",
        "name":"7 Juni Plassen",
        "address":"7 Juni Plassen",
        "lat":59.9150596,
        "lon":10.7312715,
        "capacity":15
      },
      {  
        "station_id":"610",
        "name":"Sotahjørnet",
        "address":"Sotahjørnet",
        "lat":59.9099822,
        "lon":10.7914482,
        "capacity":20
      }
    ]
  }
}

EDIT1

I realise that I wrote a lot of text making a mess a little bit. Shortly- I want to display a location of bike stations on my map( I have lat and lan location from API). How I can display it using API. There is 150+ locations and adding all of them by hand it's not a deal, also there is chance that something can be added/deleted in future.

For a marker of location I hard-scripted a red circle.

Upvotes: 3

Views: 3847

Answers (1)

kboul
kboul

Reputation: 14570

You can display them using an API by simply fetching the data like below and then iterate over them and display markers with their popup info. Because you have hundreds of markers it will be good to use preferCanvas: true option to avoid possible bad browser performance while rendering the markers.

fetch("https://gbfs.urbansharing.com/oslobysykkel.no/station_information.json")
  .then((response) => response.json())
  .then((responseData) => {
    console.log(responseData.data);
    const stations = responseData.data.stations;

    const layerGroup = L.featureGroup().addTo(map);

    stations.forEach(({ lat, lon, name, address }) => {
      layerGroup.addLayer(
        L.marker([lat, lon], { icon }).bindPopup(
          `Name: ${name}, Address: ${address}`
        )
      );
    });

    map.fitBounds(layerGroup.getBounds());
  });

Demo

Upvotes: 3

Related Questions