Search code examples
javascriptjquerydjangotomtom

How to solve error on using tomtom mapfit?


According to this guide:https://developer.tomtom.com/blog/build-different/adding-tomtom-maps-django-app-building-front-end-map I'm trying to use the tomtom for my django project and everything is working well except the zoom part where the map should zoom according to the accordinates I gave it. The error I get the on explorer consol log is:

Uncaught (in promise) Error: `LngLatLike` argument must be specified as a LngLat instance, an object {lng: <lng>, lat: <lat>}, an object {lon: <lng>, lat: <lat>}, or an array of [<lng>, <lat>]

The code I tried to run:

     // create the map
        tt.setProductInfo('Google Map', '1.0');
       let map = tt.map({
           key: '',
           container: 'map'
       });

       // add store markers
       let bounds = []
       let storeLocations = JSON.parse("{{ locations|escapejs }}");

       for (let storeLocation of storeLocations) {
           let coordinates = [storeLocation.longitude, storeLocation.latitude];
            bounds.push(coordinates);

           // create popup to display store information when the marker is clicked
           let popup = new tt.Popup().setHTML(`
               <div class="locator-popup">
                   <h6>Store Name</h6>
                   <p>${storeLocation.name}</p>
                   <h6>Address</h6>
                   <p>${storeLocation.address}</p>
               </div>
           `);

           let marker = new tt.Marker()
               .setLngLat(coordinates)
               .setPopup(popup)
               .addTo(map);
       }

       // zoom the map to fit all markers
        map.on('load', () => {
            console.log(bounds)
            map.fitBounds(bounds, {
               padding: { top: 50, bottom:50, left: 50, right: 50 }
           });
       })

Note: I was thinking that's maybe because of the 'bounds'. So, Checked the output of 'console.log(bounds)' and the resoult is:

[Array(2)]
0: (2) [51.34912743809577, 35.701243277665895]
length: 1
lastIndex: (...)
lastItem: (...)
[[Prototype]]: Array(0)

The map should zoom while this loaded


Solution

  • fitBounds() needs two corners - southwest and northeast points. This error is more or less telling that it didn't get LngLatLike argument. But in fact it needs two of them.

    So to fix the code - if you have single store in array then you could duplicate that location in bounds array.

    Something like:

    if (bounds.length = 1) {
      bounds.push(bounds[0])
    }