JSFiddle - React, Tailwind, and code Playground
by gnijuohz
HTML
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas { height: 100% }
</style>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 8
};
var map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
google.maps.event.addListener(map, 'center_changed', function() {
checkBounds(map);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
// 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;
console.log("check bounds " + latNorth + " " + latSouth );
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) {
console.log("current center" + map.getCenter() );
var newCenter= new google.maps.LatLng( newLat ,map.getCenter().lng() );
console.log("setting new center" + newCenter);
map.setCenter(newCenter);
}
}
</script>
</head>
<body>
<div id="map-canvas"/>
</body>
</html>