偏心显示Google地图 [英] Display Google Map off center

查看:47
本文介绍了偏心显示Google地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在使用Google Maps API来显示地图,效果很好.

We're using Google Maps API to display a map, which is working fine.

我看到很多抱怨,人们地图上的标记不在中心.

I see lots of complaints where the marker on people's maps isn't in the center.

我们实际上想要相反,由于此特定地图上房屋的位置,我们希望地图稍微偏离中心,其位置及其标记都朝着地图的右上角(以说明问题),我们实际上是希望移动地图画布,而不是更改房屋的实际位置.

We actually want the opposite, due to the location of the premises on this particular map we'd like to have the map slightly off-center with the location and its marker towards the top-right corner of the map (to clarify, we want to essentially shift the map canvas, not change the actual location of the premises).

下面是我们正在使用的代码. center:latlng 是什么使地图居中,所以我知道我们需要将 center 参数更改为其他参数,但我不确定是什么.

Below is the code we're using. The center: latlng is what centers the map, so I know we need to change the center parameter to something else, but I'm not sure what.

<script src="//maps.google.com/maps/api/js?sensor=false&amp;region=GB"></script>
<script>
var geocoder1 = new google.maps.Geocoder;
geocoder1.geocode( { 'address': "360 Any Street, 12345"}, function(results, status) {
    myGeocode(results, status, 'map_canvas');
});
function myGeocode(results, status, canvas) {
    if (status == google.maps.GeocoderStatus.OK) {
        var latlng = new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng());
        var myOptions = {
            zoom: 12,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
        };
        var map = new google.maps.Map(document.getElementById(canvas), myOptions);
        var myMarker = new google.maps.Marker({ position: latlng, map: map });
    } else {
        // alert("Geocode was not successful for the following reason: " + status);
    }
}
</script>
<div id="map_canvas" style="width: 600px; height: 600px;"></div>

推荐答案

这是针对当前情况的解决方案,但是当缩放更改时,不会设置中心以获取所需的视图.如果您想要更优雅的解决方案,则可以在每次zoom_changed事件之后使用包含缩放值的公式来重置中心.

This is a solution for the current case, but won't set the center to get the desired view when zoom changes. If you want more elegant solution, you can reset the center after each zoom_changed event with a formula including zoom value.

...
var myMarker = new google.maps.Marker({ position: latlng, map: map });
var offsetLat = -0.02;
var offsetLng = -0.02;
map.setCenter(new google.maps.LatLng((map.getCenter().lat() + offsetLat) , (map.getCenter().lng() + offsetLng))); 
} else {
...

这篇关于偏心显示Google地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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