Search code examples
titaniumregion

Centering Map around multiple points (annotations) on the map - Titanium mobile


I have multiple annotations on the map - although the user may need to scroll to see them. I want the user to be able to select a button to fit them all on the map - eliminating the need to scroll/manually resize.

I have determined the min. and max. latitudes and longitudes (e.g minLat, maxLat, minLong, maxLong) for the points I want to show on the map.

I'm struggling, however, with the specific formula to use to get the longitude and latitude properties to pass to mapview.setLocation. Any pointers on what formula I can use?


Solution

  • I have made a function for the same requirement. You can test and let me know if it gives some error:

    function setMarkersWithCenter(map,latiarray,longiarray)
    {
        if(latiarray.length != longiarray.length)
            return;
        var total_locations = latiarray.length;
        var minLongi = null, minLati = null, maxLongi = null, maxLati = null;
        var totalLongi = 0.0, totalLati = 0.0;
    
        for(var i = 0; i < total_locations; i++) 
        {
            if(minLati == null || minLati > latiarray[i]) {
                minLati = latiarray[i];
            }
            if(minLongi == null || minLongi > longiarray[i]) {
                minLongi = longiarray[i];
            }
            if(maxLati == null || maxLati < latiarray[i]) {
                maxLati = latiarray[i];
            }
            if(maxLongi == null || maxLongi < longiarray[i]) {
                maxLongi = longiarray[i];
            }
        }
    
        var ltDiff = maxLati-minLati;
        var lgDiff = maxLongi-minLongi;
        var delta = ltDiff>lgDiff ? ltDiff : lgDiff;
        if(total_locations>0 && delta>0)
        {
            map.setLocation({
                animate : true,
                latitude:((maxLati+minLati)/2),
                longitude:((maxLongi+minLongi)/2),
                latitudeDelta:delta,
                longitudeDelta:delta,
            }); 
        }
    
    }
    

    Hope it helps.