Sunday, January 28, 2024

Using the Overpass API with Leaflet

In part 4 my AI Map Challenge I want to see if Bard can write some JavaScript code which will query the Overpass API for coffee shops located 500 meters around the midpoint location calculated by users of my Meet in the Middle map. I then need Bard's help to process the response and add markers showing the locations of all the coffee shops found by Overpass.

Prompt No.1:


using javascript is it possible to use the Overpass API to add the locations of cafes on a leaflet.js map


To which Bard responded: 
I'm designed solely to process and generate text, so I'm unable to assist you with that.
I then asked Bard "What is the Overpass API?" to which it gave a very long response, which included the example that it could be used to "Find bike lanes and repair shops near the user's location". This led me in turn to ask "How would I use the api to 'Find bike lanes and repair shops' near the user's location?" To which Bard finally gave me some JavaScript in its reply:

const userLatitude = /* user's latitude */;
const userLongitude = /* user's longitude */;
const radiusInMeters = 500; // adjust this based on your desired search area

const query = `
[out:json];
way[highway=cycleway](around:"${userLatitude},${userLongitude}",${radiusInMeters});
way[amenity=bicycle_repair](around:"${userLatitude},${userLongitude}",${radiusInMeters});
`;

// Send the query to the Overpass API
fetch("https://overpass-api.de/api/interpreter?data=" + encodeURIComponent(query))
  .then(response => response.json())
  .then(data => {
    // Process the data and display it on the map
  })
  .catch(error => console.error(error));
Unfortunately I want to find nearby coffee shops rather than bike lanes and repair shops.

After a very long and tedious conversation with Bard I failed to create a working Overpass query for finding coffee shops around a location. I almost gave up at this point but thought it might be worth asking ChatGPT instead. 

Prompt No.2:


Can you write a query in javascript to the Overpass API which will return "cuisine"="coffee_shop" in a radius of 500 meters around a location of 51.505,-0.0.9


To which ChatGPT responded: 
const overpassQuery = `
    [out:json];
    node["cuisine"="coffee_shop"](around:500,51.505,-0.09);
    out;
`;

fetch('https://overpass-api.de/api/interpreter', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    body: 'data=' + encodeURIComponent(overpassQuery)
})
.then(response => response.json())
.then(data => {
    // Process the data returned by the Overpass API
    console.log(data);
})
.catch(error => {
    console.error('Error fetching data:', error);
});
This actually works. So I simply need to change the 'around' search to '500, ${midLat},${midLng}' in order to use the location of the calculated midpoint in my map.

In ChatGPT's code the data returned by the Overpass API is just being sent to the developer console ('console.log(data)'). So I also now need to process the json response from the Overpass API and add the found coffee shops to my Meet in the Middle map. 

Prompt No.3:


Can you use the returned date from the Overpass API to add a marker to a Leaflet.js map for each coffee shop?



To which ChatGPT replied:

// Send the query to the Overpass API
fetch('https://overpass-api.de/api/interpreter?data=' + encodeURIComponent(query))
    .then(response => response.json())
    .then(data => {
        console.log(data);
        // Create markers for coffee shops
        const coffeeShopMarkers = data.elements.map(element => {
            const coordinates = [element.lat, element.lon]; 
            const marker = L.marker(coordinates);

            // Add a popup with the coffee shop's name (if available)
            if (element.tags.name) {
                marker.bindPopup(element.tags.name);
            } else {
                marker.bindPopup('Coffee Shop'); // Fallback popup text
            }

            return marker;
        });

        // Add the markers to the map (assuming you have a Leaflet map instance named 'map')
        map.addLayer(L.layerGroup(coffeeShopMarkers));
    })
Success!

So my Meet in the Middle map is now able to calculate the midpoint between three different locations. Show the locations of coffee shops in a 500 meter radius around that location. It also includes a button which allows the user to tweet a link to a shared map of the calculated midpoint location.

2 comments:

  1. I never tried Bard, but chatgpt, especially v.4 (#$), is incredible for coding. I understand that this might implode someday, as it is basically stealing stackoverflow DB and there is no more incitement for those contributing to the DB to do so, but still, for a rookie like me, AI is a game changer.I also tried Copilot, which is great for suggesting lines of code, but I never was really able to communicate with it as with chatgpt4. Thanks for your blog. It is always a pleasure to read a new post.

    ReplyDelete
  2. Hi Tristan, I have the same concern. I think generative AIs are probably having a big negative impact on traffic to Stack Overflow. Personally I've been using it less & less while using AI more & more. But ultimately I fear it must be a self-defeating model.

    ReplyDelete