Search code examples
androidgoogle-mapsandroid-mapviewcenteroffset

Mapview on tablet: How can I center the map with an offset?


Hint: Here is a similar post with HTML.

In the current tablet implementation of my app, I have a fullscreen MapView with some informations displayed in a RelativeLayout on a left panel, like this:

(My layout is quite trivial, and I guess there is no need to post it for readability)

enter image description here

The problem comes when I want to center the map on a specific point... If I use this code:

mapController.setCenter(point);

I will of course get the point in the center of the screen and not in the center of the empty area.

I have really no idea where I could start to turn the offset of the left panel into map coordinates...

Thanks a lot for any help or suggestion


Solution

  • You can achive your objective by getting the map coordinates from top-left and bottom-right corners and divide it by the screen size, to get the value per pixel.

    Then you just need to multiply by the offset and add it to the original center.

    Example code:

    private void centerMap(GeoPoint center, int offX, int offY){
        GeoPoint tl = mapView.getProjection().fromPixels(0, 0);
        GeoPoint br = mapView.getProjection().fromPixels(mapView.getWidth(), mapView.getHeight());
    
        int newLon = offX * (br.getLongitudeE6() - tl.getLongitudeE6()) / mapView.getWidth() + center.getLongitudeE6(); 
        int newLat = offY * (br.getLatitudeE6() - tl.getLatitudeE6()) / mapView.getHeight() + center.getLatitudeE6();
    
        mapController.setCenter(new GeoPoint(newLat, newLon));
    
    }
    

    To use, you call the above method with your original center and both offsets (x and Y) to apply.

    Note: as written, the code above move map left for positive offset values, and right for negative offset values. From the screen in your question you will need to use negative offset, to move map left, and a zero offset for Y.

    Regards