Fetching data from Foursquare to make a map

298 Views Asked by At

I am trying to create a map with the 5 closest locations to the user. I am having trouble connecting to foursquare & fetching the data to show on my map for the 5 businesses I have in the drop-down menu. Any suggestions? on the bottom, the coffee shop location is the example foursquare gives using a promise chaining syntax which I could not get to work for me. I have also tried async/ await syntax but could not get that to work either, not sure if I'm missing something in my HTML for this.

// create map
window.onload = function () {
  var map = L.map("map", {
    center: [35.83719, -78.81413],
    zoom: 13,
    businesses: [],
    markers: {},
  });
  // streetmap tiles
  L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
    maxZoom: 19,
    attribution:
      '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
  }).addTo(map);
  // adding a marker
  L.marker([35.83719, -78.81413])
    .addTo(map)
    .bindPopup("You Are Here")
    .openPopup();
};
const options = {
  method: "GET",
  headers: {
    Accept: "application/json",
    Authorization: "fsq3MjY0JVfpk7e9/c5Oz9FOd+1UW1FgFWC9gCvf7FbLFM8=",
  },
};
//marker for I Am Here marker
//const marker = L.marker([48.87007, 2.346453]);
//marker.addTo(myMap).bindPopup("<p1><b>You Are Here</b></p1>").openPopup();
document.getElementById("submit").addEventListener("click", async (event) => {
  event.preventDefault();
  let business = document.getElementById("businesses").value;
  console.log(businesses);
});

// form categories
const coffee = L.layerGroup([]).addTo(map);
const hotel = L.layerGroup([]).addTo(map);
const food = L.layerGroup([]).addTo(map);
const nightLlife = L.layerGroup([]).addTo(map);
const stores = L.layerGroup([]).addTo(map);

fetch(
  "https://api.foursquare.com/v3/places/search?query=hotel&ll=35.91%2C-78.77&sort=DISTANCE&limit=5",
  options
)
  .then((response) => response.json())
  .then((response) => console.log(response))
  .catch((err) => console.error(err));

let limit = 5;
let lat = map.coordinates[0];
let lon = map.coordinates[1];
let response = fetch(
  `https://cors-anywhere.herokuapp.com/https://api.foursquare.com/v3/places/search?&query=${businesses}&limit=${limit}&ll=${lat}%2C${lon}`,
  options
);
let data = response.text();
let parsedData = JSON.parse(data);
let businesses = parsedData.results;

// near me
function processBusinesses(data) {
  let businesses = data.map((element) => {
    let location = {
      name: element.name,
      lat: element.geocodes.main.latitude,
      long: element.geocodes.main.longitude,
    };
    return location;
  });
  return businesses;
}

//get the users location
async function getCoords() {
  const pos = await new Promise((resolve, reject) => {
    navigator.geolocation.getCurrentPosition(resolve, reject);
  });
  return [pos.coords.latitude, pos.coords.longitude];
}
addMarkers();
for (var i = 0; i < this.businesses.length; i++) {
  this.markers = L.marker([this.businesses[i].lat, this.businesses[i].long])
    .bindPopup(`<p1>${this.businesses[i].name}</p1>`)
    .addTo(this.map);
}


// create array of businesses that will go in drop down
const latlngs = [[47.6205, -122.35], []];
const coffeeShops = { method: "GET", headers: { Accept: "application/json" } };

fetch(
  "https://api.foursquare.com/v3/places/search?query=coffee&ll=%7C%7C%3D35.91470%2C%20-78.77312&limit=5",
  options
)
  .then((response) => response.json())
  .then((response) => console.log(response))
  .catch((err) => console.error(err));

const stations = L.layerGroup([coffee, hotel, food, nightLlife, stores]).addTo(
  myMap
);
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Valeria's Map</title>
    <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A==" crossorigin="" />
    <script
      src="https://unpkg.com/[email protected]/dist/leaflet.js"
      integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA=="
      crossorigin=""
    ></script>
    <style>
      #map {
        height: 600px;
        background-color: #ccc;
      }
      .leaflet-popup-content-wrapper {
        width: 100%;
      }
    </style>
  </head>
  <body>
    <form id="dropdown">
      <label>Near You</label>
      <select id = "businesses" name="Businesses">
        <option value = "Coffee"> Coffee Shops</option>
        <option value = "Hotel">Hotels</option>
        <option value = "Food"> Food</option>
        <option value = "Night-life"> Night Life</option>
        <option value = "Stores"> Stores</option>
      </select>
      <button id="submit">Search</button>
    </form>
    </div>
    <div id="map"></div>
      <script src="index.js"></script>
  </body>
</html>

1

There are 1 best solutions below

0
Finn On

thanks for the edits. I still couldn't get a lot of your code to run but I pulled out a snippet that gets the 5 closest coffee shops from the foursquare API and adds markers to the map for each of them. I hope that helps get you started!

var map = L.map("map", {
  center: [35.83719, -78.81413],
  zoom: 13,
  businesses: [],
  markers: {},
});

L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
  maxZoom: 19,
  attribution:
    '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
}).addTo(map);

// adding a marker
L.marker([35.83719, -78.81413])
  .addTo(map)
  .bindPopup("You Are Here")
  .openPopup();

const options = {
  method: "GET",
  headers: {
    Accept: "application/json",
    Authorization: "fsq3MjY0JVfpk7e9/c5Oz9FOd+1UW1FgFWC9gCvf7FbLFM8=",
  },
};

const coffee = L.layerGroup([]).addTo(map);

fetch(
  "https://api.foursquare.com/v3/places/search?query=coffee&near&limit=5",
  options
)
  .then((response) => response.json())
  .then((response) => {
    if (response.results.length){

      // Iterate over each business retreived
      for (let i = 0; i < response.results.length; i++){

        // Get the lat, long, and name of each business from the result
        let { latitude, longitude } = response.results[i].geocodes.main;
        let { name } = response.results[i];
        console.log(`${latitude}, ${longitude}, ${name}`)

        // Create a marker for each business
        let coffeeMarker = L.marker([latitude, longitude]).bindPopup(name);

        // Add the marker to the coffee layerGroup
        coffee.addLayer(coffeeMarker);
      }

      // Just for demo- make sure added markers are within map view
      map.setView([response.results[0].geocodes.main.latitude, response.results[0].geocodes.main.longitude], 13)
    }
  })
  .catch((err) => console.error(err));
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Valeria's Map</title>
    <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A==" crossorigin="" />
    <script
      src="https://unpkg.com/[email protected]/dist/leaflet.js"
      integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA=="
      crossorigin=""
    ></script>
    <style>
      #map {
        height: 600px;
        background-color: #ccc;
      }
      .leaflet-popup-content-wrapper {
        width: 100%;
      }
    </style>
  </head>
  <body>
    <form id="dropdown">
      <label>Near You</label>
      <select id = "businesses" name="Businesses">
        <option value = "Coffee"> Coffee Shops</option>
        <option value = "Hotel">Hotels</option>
        <option value = "Food"> Food</option>
        <option value = "Night-life"> Night Life</option>
        <option value = "Stores"> Stores</option>
      </select>
      <button id="submit">Search</button>
    </form>
    </div>
    <div id="map"></div>
      <script src="index.js"></script>
  </body>
</html>