Google maps api 3 Bounds无法移动地图

时间:2016-01-20 13:46:43

标签: javascript google-maps

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

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);
});
&#13;
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
#map {
  height: 100%;
  background-color: #19191A !important;
}
&#13;
<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>
&#13;
&#13;
&#13;

经过一些调整后我确定它有点动态,但我仍然有问题,我可以向左移动。

我现在使用的代码:

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

向左或向右拖动时

1 个答案:

答案 0 :(得分:1)

您的界限不正确。

根据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.

参数应该是SW,NE。你的论点是NW,SE。你的代码:

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

代码段

&#13;
&#13;
$(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
  }]
}];
&#13;
html,
body,
#map {
  height: 100%;
  width: 100%;
}
&#13;
<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>
&#13;
&#13;
&#13;