javascript - Google map api 3 Bounds 无法移动 map

标签 javascript google-maps

您好,我正在开发一个涉及谷歌地图的项目,我目前正在尝试制作它,以便最终用户不会有重复的 map ,所以我使用边界,但当我这样做时,我无法平移出于某种原因。

OLD code here

$(document).ready(function() {

  var dev = true;
  var zoomed = false;

  //Google Maps JS
  //Map styling
  var Mapstyle = [{
    "stylers": [{
      "visibility": "simplified"
    }]
  }, {
    "stylers": [{
      "color": "#19191a"
    }]
  }, {
    "featureType": "water",
    "stylers": [{
      "color": "#1a1a1a"
    }, {
      "lightness": 8
    }]
  }, {
    "elementType": "labels.text.fill",
    "stylers": [{
      "visibility": "on"
    }, {
      "lightness": 25
    }]
  }];

  //Set Map
  function init() {

    //Calculate Center of the world when map loads
    var w = window.innerWidth;

    var mapOptions = {
      minZoom: getZoom(w),
      zoom: getZoom(w),
      center: getLatLng(w),
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      disableDefaultUI: true,
      styles: Mapstyle
    };
    var map = new google.maps.Map(document.getElementById('map'), mapOptions);


    //Get visitors location and place maker on top of it
    $.getJSON('http://freegeoip.net/json/', function(location) {
      getCountry(location.country_code);
    });

    function getCountry(country) {
      geocoder = new google.maps.Geocoder();
      geocoder.geocode({
        'address': country
      }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          var marker = new google.maps.Marker({
            map: map,
            animation: google.maps.Animation.DROP,
            position: results[0].geometry.location
          });
        } else {
          alert("Geocode was not successful for the following reason: " + status);
        }
      });
    }

    //Testing bounds
    google.maps.event.addListenerOnce(map, 'tilesloaded', function() {
      allowedBounds = map.getBounds();
      if (dev === true) {
        console.log(allowedBounds);
      }
      google.maps.event.addListener(map, 'center_changed', function() {
        checkBounds(allowedBounds);
      });
    });

    // Limit map area
    function checkBounds(allowedBounds) {

      if (!allowedBounds.contains(map.getCenter())) {
        var C = map.getCenter();
        var X = C.lng();
        var Y = C.lat();

        var AmaxX = allowedBounds.getNorthEast().lng();
        var AmaxY = allowedBounds.getNorthEast().lat();
        var AminX = allowedBounds.getSouthWest().lng();
        var AminY = allowedBounds.getSouthWest().lat();

        if (X < AminX) {
          X = AminX;
        }
        if (X > AmaxX) {
          X = AmaxX;
        }
        if (Y < AminY) {
          Y = AminY;
        }
        if (Y > AmaxY) {
          Y = AmaxY;
        }

        map.setCenter(new google.maps.LatLng(Y, X));
      }
    }

    //Resize Function
    google.maps.event.addDomListener(window, "resize", function() {
      if (zoomed === false) {
        map.setZoom(getZoom(4));
        zoomed = false;
      } else {
        var center = map.getCenter();
        google.maps.event.trigger(map, "resize");
        map.setCenter(center);
      }
    });
  }

  function getZoom(w) {
    if (w <= 512) {
      if (dev === true) {
        console.log("Zoom level 1");
      }
      return 1;
    } else if (w > 512 && w <= 1024) {
      if (dev === true) {
        console.log("Zoom level 2")
      }
      return 2;
    } else if (w > 1024 && w <= 2048) {
      if (dev === true) {
        console.log("Zoom level 3")
      }
      return 3;
    } else if (w > 2048 && w <= 4096) {
      if (dev === true) {
        console.log("Zoom level 4")
      }
      return 4;
    } else if (w > 4096 && w <= 8192) {
      if (dev === true) {
        console.log("Zoom level 5")
      }
      return 3;
    }
  }

  function getLatLng(w) {
    if ((w <= 512) || (w > 512 && w <= 1024)) {
      var smallLatLng = new google.maps.LatLng(0, 0);
      return smallLatLng;
    } else {
      var normalLatLng = new google.maps.LatLng(25, 0);
      return normalLatLng;
    }
  }
  google.maps.event.addDomListener(window, 'load', init);
});
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
#map {
  height: 100%;
  background-color: #19191A !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3"></script>
<div id=map></div>

好吧,经过一些调整,我让它变得更加动态,但我仍然遇到可以向左平移的问题。

我现在使用的代码:

google.maps.event.addListenerOnce(map, 'tilesloaded', function () {
        allowedBounds = map.getBounds();
        if(dev === true ) { console.log(allowedBounds); }
        google.maps.event.addListener(map, 'center_changed', function () {
            checkBounds(allowedBounds);
        });
    });

    // Limit map area
    function checkBounds(allowedBounds) {

        if (!allowedBounds.contains(map.getCenter())) {
            var C = map.getCenter();
            var X = C.lng();
            var Y = C.lat();

            var AmaxX = allowedBounds.getNorthEast().lng();
            var AmaxY = allowedBounds.getNorthEast().lat();
            var AminX = allowedBounds.getSouthWest().lng();
            var AminY = allowedBounds.getSouthWest().lat();

            if (X < AminX) { X = AminX; }
            if (X > AmaxX) { X = AmaxX; }
            if (Y < AminY) { Y = AminY; }
            if (Y > AmaxY) { Y = AmaxY; }

            map.setCenter(new google.maps.LatLng(Y, X));
        }
    }

仍然给出这个 enter image description here

向左或向右拖动时

最佳答案

你的界限不正确。

根据documentation for the constructor for a google.maps.LatLngBounds object:

Constructor
LatLngBounds(sw?:LatLng, ne?:LatLng)    Constructs a rectangle from the points at its south-west and north-east corners.

The arguments should be SW, NE. Your arguments are NW, SE. Your code:

var allowedBounds = new google.maps.LatLngBounds(
    new google.maps.LatLng(85, -180), // top left corner of map
    new google.maps.LatLng(-85, 180) // bottom right corner
);

应该是:

var allowedBounds = new google.maps.LatLngBounds(
  new google.maps.LatLng(-85, -180), // bottom left corner of map (SW)
  new google.maps.LatLng(85, 180) // top right corner (NE)
);

proof of concept fiddle

代码片段:

$(document).ready(function() {
  //Set Map
  function init() {

    //Calculate Center of the world when map loads
    var w = window.innerWidth;

    var mapOptions = {
      minZoom: getZoom(w),
      zoom: getZoom(w),
      center: getLatLng(w),
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      disableDefaultUI: true,
      styles: Mapstyle
    };
    var map = new google.maps.Map(document.getElementById('map'), mapOptions);

    //Testing bounds
    var allowedBounds = new google.maps.LatLngBounds(
      new google.maps.LatLng(-85, -180), // bottom left corner of map (SW)
      new google.maps.LatLng(85, 180) // top right corner (NE)
    );

    var lastValidCenter = map.getCenter();

    google.maps.event.addListener(map, 'center_changed', function() {
      if (allowedBounds.contains(map.getCenter())) {
        lastValidCenter = map.getCenter();
        return;
      }

      map.panTo(lastValidCenter);
    });
    
    
    //Get visitors location and place maker on top of it
    $.getJSON('http://freegeoip.net/json/', function(location) {
      getCountry(location.country_code);
    });

    function getCountry(country) {
      geocoder = new google.maps.Geocoder();
      geocoder.geocode({
        'address': country
      }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          var marker = new google.maps.Marker({
            map: map,
            animation: google.maps.Animation.DROP,
            position: results[0].geometry.location
          });
        } else {
          alert("Geocode was not successful for the following reason: " + status);
        }
      });
    }

    //Resize Function
    google.maps.event.addDomListener(window, "resize", function() {
      var center = map.getCenter();
      google.maps.event.trigger(map, "resize");
      map.setCenter(center);
    });
  }

  function getZoom(w) {
    if (w <= 512) {
      return 1;
    } else if (w > 512 && w <= 1024) {
      return 2;
    } else if (w > 1024 && w <= 2048) {
      return 3;
    } else if (w > 2048 && w <= 4096) {
      return 4;
    } else if (w > 4096 && w <= 8192) {
      return 3;
    }
  }

  function getLatLng(w) {
    if ((w <= 512) || (w > 512 && w <= 1024)) {
      var smallLatLng = new google.maps.LatLng(0, 0);
      console.log("small");
      return smallLatLng;
    } else {
      var normalLatLng = new google.maps.LatLng(25, 0);
      console.log("big");
      return normalLatLng;
    }
  }
  google.maps.event.addDomListener(window, 'load', init);
});

//Google Maps JS
//Map styling
var Mapstyle = [{
  "stylers": [{
    "visibility": "simplified"
  }]
}, {
  "stylers": [{
    "color": "#19191a"
  }]
}, {
  "featureType": "water",
  "stylers": [{
    "color": "#1a1a1a"
  }, {
    "lightness": 8
  }]
}, {
  "elementType": "labels.text.fill",
  "stylers": [{
    "visibility": "on"
  }, {
    "lightness": 25
  }]
}];
html,
body,
#map {
  height: 100%;
  width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>

关于javascript - Google map api 3 Bounds 无法移动 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34901795/

相关文章:

ios - 如何停止 GMSMapView 渲染器?

javascript - 无法理解backbone.js教程示例

javascript - 将 DOM 树不同部分的元素显示在另一个元素旁边

php - 从数据库获取 Google map 标记到 map

javascript - Ruby 生成的 javascript 文件不会在页面刷新时更新

google-maps - 在 Google Maps Engine 中查找 map 和图层 ID

javascript - JavaScript 中的对象没有返回值

javascript - 让 child 知道它应该在 React 中更新它的状态

javascript对象方法定义区别

python - 从 CSV 为 Google map 创建 KML 文件