Search code examples
javajavascriptgoogle-maps-api-3latitude-longitudedelta

Java/Javascript Calculate fitbounds SW/NE with user location in center


What I am trying to do is trying to calculate SW, NE of given locations and then delta with user's centre location. which will result to fitbounds all locations and user's location in centre.

but unfortunaly it is not working any one quick suggestion ?

public void calculateMapFitBounds(GeoLocation userLocation, List<GeoLocation > contents, Map<String, GeoLocation> latlngBounds){

        //SW
        double minLat = userLocation.getLatitude();
        double minLng = userLocation.getLongitude();

        //NE
        double maxLat = -9999;
        double maxLng = -9999;

        for(GeoLocation content: contents){

            /*
             * Populating Top left cordinate (SW)
             */
            minLat = Math.min(minLat, content.getLatitude());
            minLng = Math.min(minLng, content.getLongitude());

            /*
             * Populating Bottom right cordinate (NE)
             */
            maxLng = Math.max(maxLng, content.getLongitude()) ;
            maxLat = Math.max(maxLat, content.getLatitude());
        }

        /*
         * Calculating Delta fit bounds
         */

        double latDelta = Math.max(Math.abs(minLat - userLocation.getLatitude()), Math.abs(maxLat-userLocation.getLatitude()));

        double lngDelta = Math.max(Math.abs(maxLng - userLocation.getLongitude()), Math.abs(minLng - userLocation.getLongitude()));

        //Calculating SW
        minLat = userLocation.getLatitude()+ latDelta;
        minLng = userLocation.getLongitude()+ lngDelta;

        latlngBounds.put("swLatLng", new GeoLocation(minLat, minLng));


        //Calculating NE
        maxLat = userLocation.getLatitude()- latDelta;
        maxLng = userLocation.getLongitude()-lngDelta;

        latlngBounds.put("neLatLng", new GeoLocation(maxLat, maxLng));

    }

Later in javascript i want to use as follows

var swLatLn = new google.maps.LatLng($!swLatLng.latitude, $!swLatLng.longitude, false);
        var neLatLn = new google.maps.LatLng($neLatLng.latitude, $neLatLng.longitude, false);

        var bounds = new google.maps.LatLngBounds(swLatLn, neLatLn);
        googleMap.fitBounds(bounds);

Solution

  • Wrong signs (below they are corrected):

    //Calculating SW
    minLat = userLocation.getLatitude() - latDelta;
    minLng = userLocation.getLongitude()- lngDelta;
    
    
    //Calculating NE
    maxLat = userLocation.getLatitude() + latDelta;
    maxLng = userLocation.getLongitude()+ lngDelta;
    

    But you definitely should tell what the problem is and whether there are error messages in the browser error console.

    ps: there is an easier way for API v3 https://stackoverflow.com/a/2205577/1164491