Search code examples
here-api

HERE MAPS Javascript api getboundingbox returning null even with multiple markers added to group


So with the code below, I get the markers just fine. However bbox is null and I cannot figure out why. Any ideas? The markers are clearly valid. Is it the image in the marker causing problems?

error I get is:

Uncaught InvalidArgumentError: H.map.ViewModel#setLookAtData (Argument #0 bounds)
    at new D (https://js.api.here.com/v3/3.1/mapsjs-core.js:43:977)
    at ul.Yb (https://js.api.here.com/v3/3.1/mapsjs-core.js:341:200)
    at showEvents (file:///C:/Users/Brian/source/repos/dnktechapi/dnktechapi/searchform.html:201:21)
    at HTMLButtonElement.onclick (file:///C:/Users/Brian/source/repos/dnktechapi/dnktechapi/searchform.html:55:64)
var icon = new H.map.Icon(svgMarkup);   
    var group = new H.map.Group();


    fetch(url)
        .then((response) => response.json())
        .then((data) => {
            console.log(data['events']);
            for(let i=0; i < data['events'].length; i++)
            {
                var count = i +1;
                console.log(data['events'][i]['lat']);
                var svgMarkup = '<svg width="24" height="24" ' +
                'xmlns="http://www.w3.org/2000/svg">' +
                '<rect stroke="white" fill="#1b468d" x="1" y="1" width="22" ' +
                'height="22" /><text x="12" y="18" font-size="12pt" ' +
                'font-family="Arial" font-weight="bold" text-anchor="middle" ' +
                'fill="white">' + count + '</text></svg>';

                var icon = new H.map.Icon(svgMarkup);   
                
                // Create a marker using the previously instantiated icon:
                var marker = new H.map.Marker({ lat: data['events'][i]['lat'], lng: data['events'][i]['lng']}, { icon: icon });

                // Add the marker to the map:
                map.addObject(marker);
            
                group.addObject(marker);
                
            }
        });
        

    
    map.addObject(group);
    console.log(group);
    var bbox = group.getBoundingBox();
    
    console.log(bbox);
    
    map.getViewModel().setLookAtData({
        bounds: bbox
    }); 


Solution

  • Your code that addss the group and tries to get the bounding box is running immediately and not after your fetch call. Your fetch call is asynchronous which means that while that network request is going on, the browser continued on and added the empty group. One quick fix would be to move the lines from map.addObject(group) to the end into the handler for the fetch call (but after the loop of course).