Image near coordinates

I am trying to use Mapillary JS to show a mapillary window, starting with a image closest possible to the given coordinates. Any suggestions on how to fix it? My code just gives “No images found near the coordinates.” in the console. I call the page like this:
mapillary.html?lon=15.968909217037435&lat=59.520650950825

The code:

<!DOCTYPE html>
<html>
<head>
    <title>Mapillary Viewer</title>
    <style>
        #mly { width: 100%; height: 500px; }
    </style>
    <script src="https://unpkg.com/mapillary-js@4.1.2/dist/mapillary.js"></script>
    <link href="https://unpkg.com/mapillary-js@4.1.2/dist/mapillary.css" rel="stylesheet" />
</head>
<body>
    <div id="mly" style="width: 600px; height: 300px;"></div>

    <script>
    window.onload = function() {
        // Initialize the viewer
        var viewer = new mapillary.Viewer({
            accessToken: 'TOKEN',
            container: 'mly',
            component: {
                cover: false,
            },
        });

        // Get the coordinates from the URL
        var urlParams = new URLSearchParams(window.location.search);
        var lat = parseFloat(urlParams.get('lat'));
        var lon = parseFloat(urlParams.get('lon'));

        console.log('Latitude:', lat);
        console.log('Longitude:', lon);

        // Fetch the closest image key
        fetch(`https://graph.mapillary.com/images?access_token=TOKEN&closeto=${lon},${lat}&radius=600&limit=1`)
    .then(response => response.json())
    .then(data => {
        console.log('API Response:', data); // Log the entire response
        if (data.features && data.features.length > 0) {
            var imageKey = data.features[0].properties.key;
            console.log('Image Key:', imageKey);
            viewer.moveTo(imageKey).catch(function(error) {
                console.error('Error moving to coordinates:', error);
            });
        } else {
            console.error('No images found near the coordinates.');
        }
    })
    .catch(error => {
        console.error('Error fetching image key:', error);
        error.text().then(errorMessage => {
            console.error('Error message:', errorMessage);
        });
    });

        // Adds event listener for navigation
        viewer.on('nodechanged', function(node) {
            console.log('Node changed:', node);
        });
    };
    </script>
</body>
</html>

And I just get this in the console:
Latitude: 59.520650950825
Longitude: 15.968909217037435
API Response: {data: Array(0)}
No images found near the coordinates.

Ok, I found out that the “closeto” function was from v3 of the API. When adapting my code for v4, I got something like this. Seems to work:

var bbox = `${lon-0.01},${lat-0.01},${lon+0.01},${lat+0.01}`;
fetch(`https://graph.mapillary.com/images?access_token=TOKEN&bbox=${bbox}&limit=1`)
    .then(response => response.json())
    .then(data => {
        console.log('API Response:', data); // Log the entire response
        if (data.data && data.data.length > 0) {
            var imageKey = data.data[0].id;
            console.log('Image Key:', imageKey); // Log the image key
            viewer.moveTo(imageKey).catch(function(error) {
                console.error('Error moving to coordinates:', error);
            });
        } else {
            console.error('No images found near the coordinates.');
        }
    })
    .catch(error => {
        console.error('Error fetching image key:', error);
    });
3 Likes

Thank you for posting the solution, leif. This should be on page 1 of the MapillaryJS documentation. All their examples have a hard-coded imageID, which is useless in the real world.

@nikola - what do you think about including this in the Mapillary JS documentation?

@oscarlorentzon Do you think this could be one of the examples in the Mapillary JS docs?

I found this post helpful and wired up the suggested closeto workaround, but quickly noticed the viewer rarely if ever opened to my target location and instead picked random points nearby. After lots of unsuccessful troubleshooting, I rendered markers into the map to depict my source point, the bbox extents, and the matched image point. Two issues seem to affect the approach presented in this post. First, expanding the latitude and longitude by a constant value results in non-uniform/symmetrical growth. Second, the bounding box is way bigger than expected, seemingly at km rather than meter scale. I could be way off and missed something obvious, but wanted to share in case anyone else has my experience.

I created a leaflet (https://codepen.io/lewin76/pen/myyvYrG) to share what I was seeing and the basic fix. The red bounds in the leaflet are this approach, the green a more geospatial one. Although I could have just reduced the growth value (0.01) and likely had decent results in the regions I’m interested in, more extreme latitudes will experience more extreme distortion. With the alternative algorithm in place, I’m seeing consistent and expected behavior from the viewer and thought it worth sharing.

Ideally this whole approach would go away, and Mapillary would expose a mechanism to center the viewer on a point of interest and none of this overhead and complexity would be needed.

1 Like