如何在谷歌地图api V3中偏移中心点 [英] How to offset the center point in Google maps api V3

查看:37
本文介绍了如何在谷歌地图api V3中偏移中心点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张 Google 地图,上面有一个半透明面板,覆盖了该区域的一部分.我想调整地图的中心点以考虑到部分被遮挡的地图部分.见下图.理想情况下,放置十字准线和图钉的位置将是地图的中心点.

I have a Google map with a semi transparent panel covering a portion of the area. I would like to adjust the center point of the map to take into account the portion of the map that is partially obscured. See the image below. Ideally, where the crosshairs and pin are placed would be the center point of the map.

我希望这是有道理的.

原因很简单:缩放时需要将地图居中放置在十字准线上,而不是 50% 50%.此外,我将在地图上绘制标记并按顺序移动它们.当地图以它们为中心时,它们也需要处于偏移位置.

The reason is simple: When you zoom it needs to center the map over the crosshair rather than at 50% 50%. Also, I will be plotting markers on the map and moving through them in sequence. When the map centers on them, they also need to be at the offset position.

提前致谢!

推荐答案

这不是特别困难,一旦你找到 相关的先前答案.

This is not particularly difficult once you find the relevant previous answer.

您需要将地图的中心转换为其世界坐标,找到地图需要居中的位置以将明显中心放在您想要的位置,然后重新居中地图使用真实中心.

You need to convert the centre of the map to its world co-ordinates, find where the map needs to be centered to put the apparent centre where you want it, and re-centre the map using the real centre.

API 将始终将地图居中于视口的中心,因此在使用 map.getCenter() 时需要小心,因为它会返回真实的中心,而不是明显的中心.我想可以重载 API 以便替换它的 getCenter()setCenter() 方法,但我还没有这样做.

The API will always centre the map on the centre of the viewport, so you need to be careful if you use map.getCenter() as it will return the real centre, not the apparent centre. I suppose it would be possible to overload the API so that its getCenter() and setCenter() methods are replaced, but I haven't done that.

代码如下.在线示例.在示例中,单击按钮会将地图的中心(那里有一个路口)向下移动 100 像素并向左移动 200 像素.

Code below. Example online. In the example, clicking the button shifts the centre of the map (there's a road junction there) down 100px and left 200px.

function offsetCenter(latlng, offsetx, offsety) {

    // latlng is the apparent centre-point
    // offsetx is the distance you want that point to move to the right, in pixels
    // offsety is the distance you want that point to move upwards, in pixels
    // offset can be negative
    // offsetx and offsety are both optional

    var scale = Math.pow(2, map.getZoom());

    var worldCoordinateCenter = map.getProjection().fromLatLngToPoint(latlng);
    var pixelOffset = new google.maps.Point((offsetx/scale) || 0,(offsety/scale) ||0);

    var worldCoordinateNewCenter = new google.maps.Point(
        worldCoordinateCenter.x - pixelOffset.x,
        worldCoordinateCenter.y + pixelOffset.y
    );

    var newCenter = map.getProjection().fromPointToLatLng(worldCoordinateNewCenter);

    map.setCenter(newCenter);

}

这篇关于如何在谷歌地图api V3中偏移中心点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆