开发者

how to calculate google maps zoom level for a bounding box in java

开发者 https://www.devze.com 2023-01-26 12:48 出处:网络
I need to get the google maps z开发者_C百科oom level for a bounding box in the server side (that is coded in java) any ideas?@Peter Actually there is something you can do on the server side using Java

I need to get the google maps z开发者_C百科oom level for a bounding box in the server side (that is coded in java) any ideas?


@Peter Actually there is something you can do on the server side using Java. You can calculate the minimum and maximum latitude/longitude values from your bounding box, and then use the following code:

int zoomLevel;
double latDiff = latMax - latMin;
double lngDiff = lngMax - lngMin;

double maxDiff = (lngDiff > latDiff) ? lngDiff : latDiff;
if (maxDiff < 360 / Math.pow(2, 20)) {
    zoomLevel = 21;
} else {
    zoomLevel = (int) (-1*( (Math.log(maxDiff)/Math.log(2)) - (Math.log(360)/Math.log(2))));
    if (zoomLevel < 1)
        zoomLevel = 1;
}

This worked well for my square Google map of 320x320 pixels, with ZOOM_SCALING_FACTOR = 0.3838. This formula should work correctly for ANY square Google map. The reason you see log_2 being used is that a Google map doubles in size every time the zoom level increases by 1. I also handle the edge cases where the points are almost coincident with each other (zoomLevel = 21), and where the entire globe is the desired zoom (zoomLevel = 1).

The nice thing about doing this server side is that you have freed your JavaScript engine from doing complex (and potentially wasteful) math which could slow down the page load and worsen the user experience.


Google maps is used via a javascript library that runs on the client side (inside browser). There is nothing you can do on the server side.

You can however look at the bounding box size in javascript (on the client side) and set zoom level accordingly.

I'm curious: what are you doing with google maps on the server side?

0

精彩评论

暂无评论...
验证码 换一张
取 消