Search OSM Places for cities using the Geoapify Places API.

This code sample shows how to get places of a chosen category for a city using Geoapify Location services

by Geoapify

HTML

<p>
 Search "<span id="category"></span>" in <span id="city"></span>
</p>

<p>
  <input value="Start" id='button' type="button">
</p>

CSS

.after-search {
  display: none;
}

JavaScript

// The API Key is restricted to JSFiddle website
// Get your own API Key on https://myprojects.geoapify.com
const myAPIKey = "6dc7fb95a3b246cfa0f3bcef5ce9ed9a";

// get a city with Geoapify Geocoding API - https://www.geoapify.com/geocoding-api
const city = "Paris, France";
document.getElementById('city').innerHTML = city;

// query places by categories. Find the complete list of the categories on https://apidocs.geoapify.com/docs/places/#categories
const placeCategory = "commercial.books";
document.getElementById('category').innerHTML = placeCategory;

let stopped = false;
let results;

document.getElementById('button').onclick = function() {
  const state = document.getElementById('button').value;
  if (state === "Start") {
  	document.getElementById('button').value = "Stop";
    getCityData(city, myAPIKey).then((cityData) => {
      if (cityData) {
        getAllPlaces(placeCategory, cityData.place_id, myAPIKey).then((places) => {
        	results = places;
          document.getElementById('button').value = "Download results";
        });
      } else {
        console.log("The city is not found");
      }
    })
  } else if (state === "Stop") {
  	stopped = true;
  } else {
  	// Download results
    const a = document.createElement('a');
    const blob = new Blob([JSON.stringify(results)], {'type':'application\/json'});
    a.href = window.URL.createObjectURL(blob);
    a.download = `${placeCategory}-${city}-${(new Date()).toUTCString()}.json`;
    a.click();
  }
}


function getCityData(city, apiKey) {
  return fetch(`https://api.geoapify.com/v1/geocode/search?text=${encodeURIComponent(city)}&format=json&apiKey=${myAPIKey}`).then(data => data.json()).then(results => {
    const cityData = results.results.length ? results.results[0] : null;
    return cityData;
  });
}


function getAllPlaces(category, cityId, apiKey) {
  return getPlacesRecursively([], 0, category, cityId, apiKey);
}

// one Places API request returns maximum of 500 objects, so it may...