Search code examples
javaandroidgoogle-maps-markersgoogle-maps-api-2

Android - Google maps V2 - Calculate whether a marker currently not in view is North, East, South or West of screen


I'm looking to be able to calculate whether markers on my mapview that are currently not in view of the screen are positioned above, right, below or left of the screen.

I've written some code to return which markers are currently in and out of the current bounds of the screen but I'm a little bit stumped on what to do next, I'd like to know if there is any way to do this or if anyone has done this before?

Check markers in view:

//-----check markers in view
public void checkMarkersInView() {

    //get current screen bounds
    LatLngBounds currentScreen = mapView.getProjection().getVisibleRegion().latLngBounds;

    //loop through each marker
    for(Marker mMarker : marker) {

        if(currentScreen.contains(mMarker.getPosition())) {
            // marker inside visible region

        } else {
            // marker outside visible region

        }
    }
}

Thanks


Solution

  • you need to calculate bearing using those values as below.

    private double angleFromLatLng(double lat1, double long1, double lat2, double long2) {
    
        double dLon = (long2 - long1);
    
        double y = Math.sin(dLon) * Math.cos(lat2);
        double x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1)
                * Math.cos(lat2) * Math.cos(dLon);
    
        double brng = Math.atan2(y, x);
    
        brng = Math.toDegrees(brng);
        brng = (brng + 360) % 360;
        brng = 360 - brng;
    
        return brng;
    }
    

    Note: 0 degrees at North and increases in clockwise direction i.e 90 degrees for east and move on

    Also, if you have Location object (say locfirst and locsecond) that stores the values of both latitude and longitude you can use below function from Location class.

    float bearing = locfirst.bearingTo(locsecond);
    

    see the reference here.