Google Maps Api - 限制平移到div的边缘

时间:2017-01-03 08:05:48

标签: google-maps google-maps-api-3

我正在开展一个项目,我已经实施了Google地图,并且正在从数据库中放置标记。我已设法限制地图上的缩放级别,但我现在需要的是限制用户不要将地图移动到某些预定义的Lat / Lon坐标之外。我也找到了一个解决方案,但它将div的限制集中在一起。我想要实现的是地图的限制在div的末尾。

这是我目前的代码:

function initMap() {
var mapBounds = new google.maps.LatLngBounds(
    new google.maps.LatLng(55.68818174, 9.26423413),
    new google.maps.LatLng(55.69109457, 9.27277962)
);

var strictBounds = new google.maps.LatLngBounds(
    new google.maps.LatLng(55.68818174, 9.26423413), 
    new google.maps.LatLng(55.69109457, 9.27277962)
);

var mapMinZoom = 15;
var mapMaxZoom = 19;
var opts = {
    streetViewControl: false,
    tilt: 0,
    mapTypeId: google.maps.MapTypeId.HYBRID,
    center: new google.maps.LatLng(<?php echo Context::getInstance()->site->coord_lat; ?>, <?php echo Context::getInstance()->site->coord_long; ?>),
    zoom: 18,
    minZoom: 18,
    maxZoom: 19
}
var map = new google.maps.Map(document.getElementById("map"), opts);

google.maps.event.addListener(map, 'drag', function() {
    if (strictBounds.contains(map.getCenter())) return;

    // We're out of bounds - Move the map back within the bounds

    var c = map.getCenter(),
    x = c.lng(),
    y = c.lat(),
    maxX = strictBounds.getNorthEast().lng(),
    maxY = strictBounds.getNorthEast().lat(),
    minX = strictBounds.getSouthWest().lng(),
    minY = strictBounds.getSouthWest().lat();

    if (x < minX) x = minX;
    if (x > maxX) x = maxX;
    if (y < minY) y = minY;
    if (y > maxY) y = maxY;

    map.setCenter(new google.maps.LatLng(y, x));
});

listenerHandle = google.maps.event.addListener(map, 'click', function(event) {
    myLatLng = event.latLng;   
    oLat = document.getElementById("coord_lat");
    oLat.value = myLatLng.lat();
    oLon = document.getElementById("coord_long");
    oLon.value = myLatLng.lng();
});

// https://developers.google.com/maps/documentation/javascript/examples/maptype-image-overlay
var imageMapType = new google.maps.ImageMapType({
    getTileUrl: function(coord, zoom) {
        var proj = map.getProjection();
        var z2 = Math.pow(2, zoom);
        var tileXSize = 256 / z2;
        var tileYSize = 256 / z2;
        var tileBounds = new google.maps.LatLngBounds(
            proj.fromPointToLatLng(new google.maps.Point(coord.x * tileXSize, (coord.y + 1) * tileYSize)),
            proj.fromPointToLatLng(new google.maps.Point((coord.x + 1) * tileXSize, coord.y * tileYSize))
        );
        if (!mapBounds.intersects(tileBounds) || zoom < mapMinZoom || zoom > mapMaxZoom) return null;
            return "/img/map/<?php echo Context::getInstance()->site->url_name; ?>/{z}/{x}/{y}.png".replace('{z}',zoom).replace('{x}',coord.x).replace('{y}',coord.y);
    },
    tileSize: new google.maps.Size(256, 256),
    minZoom: mapMinZoom,
    maxZoom: mapMaxZoom,
    name: 'Tiles'
});

setMapPins(map);

map.overlayMapTypes.push(imageMapType);
map.fitBounds(mapBounds);
}

0 个答案:

没有答案