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

时间:2015-03-09 16:46:49

标签: google-maps openstreetmap

我正在使用谷歌地图(通过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是在代码的其他部分中定义的变量。

我应该将哪些内容添加到地图的构造函数中?

DEMO

1 个答案:

答案 0 :(得分:3)

你必须改变getTileUrl函数来规范化x方向的坐标,如example in the documentation

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
  };
}

working fiddle