How to block google maps api v3 panning in the gray zone over north pole or under south pole?

前端 未结 2 937
情歌与酒
情歌与酒 2020-12-10 09:43

Using google maps v3 javascript API i cannot find a way to block the panning of the map over the north pole or under the south pole. As an example embedded maps on this pag

相关标签:
2条回答
  • 2020-12-10 10:14

    UPDATE - The following answer doesn't look to work anymore, I suppose it's because google maps API has been upgrade. I leave the code here for reference.

    Thanks to geocodezip comments i modified Mike Williams' solution for my case.

    Here is the fiddle example

    Relevant code part:

    google.maps.event.addListener(map, 'center_changed', function() {
        checkBounds(map);
    });
    // If the map position is out of range, move it back
    function checkBounds(map) {
    
    var latNorth = map.getBounds().getNorthEast().lat();
    var latSouth = map.getBounds().getSouthWest().lat();
    var newLat;
    
    if(latNorth<85 && latSouth>-85)     /* in both side -> it's ok */
        return;
    else {
        if(latNorth>85 && latSouth<-85)   /* out both side -> it's ok */
            return;
        else {
            if(latNorth>85)   
                newLat =  map.getCenter().lat() - (latNorth-85);   /* too north, centering */
            if(latSouth<-85) 
                newLat =  map.getCenter().lat() - (latSouth+85);   /* too south, centering */
        }   
    }
    if(newLat) {
        var newCenter= new google.maps.LatLng( newLat ,map.getCenter().lng() );
        map.setCenter(newCenter);
        }   
    }
    
    0 讨论(0)
  • 2020-12-10 10:21

    Working for me with the attribute "restriction":

    new google.maps.Map(document.getElementById('#mapCanvas'), {
      zoom: 2,
      center: {lat: 0, lng: 0},
      tilt: 0,
      restriction: {
        latLngBounds: {north: 85, south: -85, west: -180, east: 180},
        strictBounds: true
      },
    });
    
    0 讨论(0)
提交回复
热议问题