如何在谷歌地图中启用水平世界重复



我正在使用谷歌地图(通过OpenStreetMap),需要水平重复世界。我认为它是默认的,但事实并非如此。

var map;
map = new google.maps.Map(element, {
    center : new google.maps.LatLng(mapa_start_X, mapa_start_Y),
    zoom : mapa_start_Z,
    mapTypeId: "OSM",
    mapTypeControl: false,
    streetViewControl: true
});
map.mapTypes.set("OSM", new google.maps.ImageMapType({
    getTileUrl: function(coord, zoom) {
        return "http://tile.openstreetmap.org/" + zoom + "/" + coord.x + "/" + coord.y + ".png";
        //return "/tile.php?z=" + zoom + "&x=" + coord.x + "&y=" + coord.y;
    },
    tileSize: new google.maps.Size(256, 256),
    name: "OpenStreetMap",
    maxZoom: 18
}));

element是DOM中的对象,mapa_start_Xmapa_start_Ymapa_start_Z是在代码的其他部分中定义的变量。

我应该向地图的构造函数添加什么?

演示

您必须更改 getTileUrl 函数以规范化 x 方向上的坐标,如文档中的示例所示。

map.mapTypes.set("OSM", new google.maps.ImageMapType({
    getTileUrl: function (coord, zoom) {
        var normalizedCoord = getNormalizedCoord(coord, zoom);
        if (!normalizedCoord) {
            return null;
        }
        return "http://tile.openstreetmap.org/" + zoom + "/" + normalizedCoord.x + "/" + normalizedCoord.y + ".png";
    },
    tileSize: new google.maps.Size(256, 256),
    name: "OpenStreetMap",
    maxZoom: 18,
    minZoom: 1
}));
// Normalizes the coords that tiles repeat across the x axis (horizontally)
// like the standard Google map tiles.
function getNormalizedCoord(coord, zoom) {
  var y = coord.y;
  var x = coord.x;
  // tile range in one direction range is dependent on zoom level
  // 0 = 1 tile, 1 = 2 tiles, 2 = 4 tiles, 3 = 8 tiles, etc
  var tileRange = 1 << zoom;
  // don't repeat across y-axis (vertically)
  if (y < 0 || y >= tileRange) {
    return null;
  }
  // repeat across x-axis
  if (x < 0 || x >= tileRange) {
    x = (x % tileRange + tileRange) % tileRange;
  }
  return {
    x: x,
    y: y
  };
}

工作小提琴

最新更新