Google지도 v3-보기 가능 영역 및 확대 / 축소 수준 제한
Google지도 v3를 특정 지역으로 제한 할 수 있습니까? 일부 영역 (예 : 국가) 만 표시하고 사용자가 다른 곳으로 슬라이드하는 것을 허용하고 싶습니다. 또한 확대 / 축소 수준을 제한하고 싶습니다. 예를 들어 수준 6과 9 사이에서만 가능합니다. 그리고 모든 기본지도 유형을 사용하고 싶습니다.
이것을 달성하는 방법이 있습니까?
StyledMap을 사용하여 확대 / 축소 수준을 제한하는 데 부분적인 성공을 거두었지만 ROADMAP 제한만으로 성공했으며 다른 기본 유형에 대한 확대 / 축소를 이런 방식으로 제한 할 수 없었습니다.
도움을 주셔서 감사합니다
dragend
이벤트를 수신 할 수 있으며 지도가 허용 된 경계를 벗어나면 다시 안으로 이동합니다. LatLngBounds
개체 에서 허용 된 경계를 정의한 다음 contains()
메서드를 사용 하여 새 위도 / 경도 중심이 경계 내에 있는지 확인할 수 있습니다.
확대 / 축소 수준을 매우 쉽게 제한 할 수도 있습니다.
다음 예를 고려하십시오. Fiddle Demo
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps JavaScript API v3 Example: Limit Panning and Zoom</title>
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false"></script>
</head>
<body>
<div id="map" style="width: 400px; height: 300px;"></div>
<script type="text/javascript">
// This is the minimum zoom level that we'll allow
var minZoomLevel = 5;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: minZoomLevel,
center: new google.maps.LatLng(38.50, -90.50),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// Bounds for North America
var strictBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(28.70, -127.50),
new google.maps.LatLng(48.85, -55.90)
);
// Listen for the dragend event
google.maps.event.addListener(map, 'dragend', function() {
if (strictBounds.contains(map.getCenter())) return;
// We're out of bounds - Move the map back within the bounds
var c = map.getCenter(),
x = c.lng(),
y = c.lat(),
maxX = strictBounds.getNorthEast().lng(),
maxY = strictBounds.getNorthEast().lat(),
minX = strictBounds.getSouthWest().lng(),
minY = strictBounds.getSouthWest().lat();
if (x < minX) x = minX;
if (x > maxX) x = maxX;
if (y < minY) y = minY;
if (y > maxY) y = maxY;
map.setCenter(new google.maps.LatLng(y, x));
});
// Limit the zoom level
google.maps.event.addListener(map, 'zoom_changed', function() {
if (map.getZoom() < minZoomLevel) map.setZoom(minZoomLevel);
});
</script>
</body>
</html>
위 예의 스크린 샷. 이 경우 사용자는 남쪽 또는 극동으로 더 이상 드래그 할 수 없습니다.
확대 / 축소 수준을 제한하는 더 좋은 방법 은 이벤트에 반응하는 대신 minZoom
/ maxZoom
옵션 을 사용하는 것입니다.
var opt = { minZoom: 6, maxZoom: 9 };
map.setOptions(opt);
또는 맵 초기화 중에 옵션을 지정할 수 있습니다. 예 :
var map = new google.maps.Map(document.getElementById('map-canvas'), opt);
참조 : Google Maps JavaScript API V3 참조
좋은 소식. 2019 년 2 월 14 일에 출시 된 Maps JavaScript API 버전 3.35부터 새 restriction
옵션을 사용 하여지도의 뷰포트를 제한 할 수 있습니다 .
문서에 따르면
MapRestriction 인터페이스
지도에 적용 할 수있는 제한입니다. 지도의 뷰포트는 이러한 제한을 초과하지 않습니다.
출처 : https://developers.google.com/maps/documentation/javascript/reference/map#MapRestriction
이제지도 초기화 중에 제한 옵션을 추가하면됩니다. 뷰포트를 스위스로 제한하는 다음 예제를 살펴보십시오.
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 46.818188, lng: 8.227512},
minZoom: 7,
maxZoom: 14,
zoom: 7,
restriction: {
latLngBounds: {
east: 10.49234,
north: 47.808455,
south: 45.81792,
west: 5.95608
},
strictBounds: true
},
});
}
#map {
height: 100%;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDztlrk_3CnzGHo7CFvLFqE_2bUKEq1JEU&callback=initMap" async defer></script>
이게 도움이 되길 바란다!
v.3 +에서 확대 / 축소를 제한하려면. 지도 설정에서 기본 확대 / 축소 수준을 추가하고 minZoom 또는 maxZoom (또는 필요한 경우 둘 다) 확대 / 축소 수준은 0 ~ 19입니다. 제한이 필요한 경우 청각 장애인 확대 / 축소 수준을 선언해야합니다. 모두 대소 문자를 구분합니다!
function initialize() {
var mapOptions = {
maxZoom:17,
minZoom:15,
zoom:15,
....
범위를 제한하는 훨씬 더 좋은 방법은 포스터 위의 포함 논리를 사용했습니다.
var dragStartCenter;
google.maps.event.addListener(map, 'dragstart', function(){
dragStartCenter = map.getCenter();
});
google.maps.event.addListener(this.googleMap, 'dragend', function(){
if (mapBounds.contains(map.getCenter())) return;
map.setCenter(this.dragStart);
});
이는지도를 특정 위치로 다시 중심을 맞추는 데 사용할 수 있습니다. 내가 필요했던 것입니다.
var MapBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(35.676263, 13.949096),
new google.maps.LatLng(36.204391, 14.89038));
google.maps.event.addListener(GoogleMap, 'dragend', function ()
{
if (MapBounds.contains(GoogleMap.getCenter()))
{
return;
}
else
{
GoogleMap.setCenter(new google.maps.LatLng(35.920242, 14.428825));
}
});
myOptions = {
center: myLatlng,
minZoom: 6,
maxZoom: 9,
styles: customStyles,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
보기 가능 영역의 제한 문제를 해결하기위한 제 변형이 있습니다.
google.maps.event.addListener(this.map, 'idle', function() {
var minLat = strictBounds.getSouthWest().lat();
var minLon = strictBounds.getSouthWest().lng();
var maxLat = strictBounds.getNorthEast().lat();
var maxLon = strictBounds.getNorthEast().lng();
var cBounds = self.map.getBounds();
var cMinLat = cBounds.getSouthWest().lat();
var cMinLon = cBounds.getSouthWest().lng();
var cMaxLat = cBounds.getNorthEast().lat();
var cMaxLon = cBounds.getNorthEast().lng();
var centerLat = self.map.getCenter().lat();
var centerLon = self.map.getCenter().lng();
if((cMaxLat - cMinLat > maxLat - minLat) || (cMaxLon - cMinLon > maxLon - minLon))
{ //We can't position the canvas to strict borders with a current zoom level
self.map.setZoomLevel(self.map.getZoomLevel()+1);
return;
}
if(cMinLat < minLat)
var newCenterLat = minLat + ((cMaxLat-cMinLat) / 2);
else if(cMaxLat > maxLat)
var newCenterLat = maxLat - ((cMaxLat-cMinLat) / 2);
else
var newCenterLat = centerLat;
if(cMinLon < minLon)
var newCenterLon = minLon + ((cMaxLon-cMinLon) / 2);
else if(cMaxLon > maxLon)
var newCenterLon = maxLon - ((cMaxLon-cMinLon) / 2);
else
var newCenterLon = centerLon;
if(newCenterLat != centerLat || newCenterLon != centerLon)
self.map.setCenter(new google.maps.LatLng(newCenterLat, newCenterLon));
});
strictBounds
new google.maps.LatLngBounds()
유형 의 객체입니다 . self.gmap
Google지도 개체 ( new google.maps.Map()
)를 저장합니다 .
It really works but don't only forget to take into account the haemorrhoids with crossing 0th meridians and parallels if your bounds cover them.
For some reason
if (strictBounds.contains(map.getCenter())) return;
didnt work for me (maybe a southern hemisphere issue). I had to change it to:
function checkBounds() {
var c = map.getCenter(),
x = c.lng(),
y = c.lat(),
maxX = strictBounds.getNorthEast().lng(),
maxY = strictBounds.getNorthEast().lat(),
minX = strictBounds.getSouthWest().lng(),
minY = strictBounds.getSouthWest().lat();
if(x < minX || x > maxX || y < minY || y > maxY) {
if (x < minX) x = minX;
if (x > maxX) x = maxX;
if (y < minY) y = minY;
if (y > maxY) y = maxY;
map.setCenter(new google.maps.LatLng(y, x));
}
}
Hope it will help someone.
One solution is like, If you know the specific lat/lng.
google.maps.event.addListener(map, 'idle', function() {
map.setCenter(new google.maps.LatLng(latitude, longitude));
map.setZoom(8);
});
If don't have specific lat/lng
google.maps.event.addListener(map, 'idle', function() {
map.setCenter(map.getCenter());
map.setZoom(8);
});
or
google.maps.event.addListener(map, 'idle', function() {
var bounds = new google.maps.LatLngBounds();
map.setCenter(bounds.getCenter());
map.setZoom(8);
});
As of middle 2016, there is no official way to restrict viewable area. Most of ad-hoc solutions to restrict the bounds have a flaw though, because they don't restrict the bounds exactly to fit the map view, they only restrict it if the center of the map is out of the specified bounds. If you want to restrict the bounds to overlaying image like me, this can result in a behavior like illustrated below, where the underlaying map is visible under our image overlay:
To tackle this issue, I have created a library, which successfully restrict the bounds so you cannot pan out of the overlay.
However, as other existing solutions, it has a "vibrating" issue. When the user pans the map aggressively enough, after they release the left mouse button, the map still continues panning by itself, gradually slowing. I always return the map back to the bounds, but that results in kind of vibrating. This panning effect cannot be stopped with any means provided by the Js API at the moment. It seems that until google adds support for something like map.stopPanningAnimation() we won't be able to create a smooth experience.
Example using the mentioned library, the smoothest strict bounds experience I was able to get:
function initialise(){
var myOptions = {
zoom: 5,
center: new google.maps.LatLng(0,0),
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
var map = new google.maps.Map(document.getElementById('map'), myOptions);
addStrictBoundsImage(map);
}
function addStrictBoundsImage(map){
var bounds = new google.maps.LatLngBounds(
new google.maps.LatLng(62.281819, -150.287132),
new google.maps.LatLng(62.400471, -150.005608));
var image_src = 'https://developers.google.com/maps/documentation/' +
'javascript/examples/full/images/talkeetna.png';
var strict_bounds_image = new StrictBoundsImage(bounds, image_src, map);
}
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("maps", "3",{other_params:"sensor=false"});
</script>
<body style="margin:0px; padding:0px;" onload="initialise()">
<div id="map" style="height:400px; width:500px;"></div>
<script type="text/javascript"src="https://raw.githubusercontent.com/matej-pavla/StrictBoundsImage/master/StrictBoundsImage.js"></script>
</body>
라이브러리는 또한 최소 확대 / 축소 제한을 자동으로 계산할 수 있습니다. 그런 다음 minZoom
지도의 속성을 사용하여 확대 / 축소 수준을 제한 합니다.
바라건대 이것은 주어진 경계를 완전히 존중하고 그 경계에서 패닝을 허용하지 않는 솔루션을 원하는 사람에게 도움이되기를 바랍니다.
이것은 도움이 될 수 있습니다.
var myOptions = {
center: new google.maps.LatLng($lat,$lang),
zoom: 7,
disableDefaultUI: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
확대 / 축소 수준은 요구 사항에 따라 사용자 지정할 수 있습니다.
참고 URL : https://stackoverflow.com/questions/3818016/google-maps-v3-limit-viewable-area-and-zoom-level
'development' 카테고리의 다른 글
"주석 처리 된"코드 체크인 (0) | 2020.08.27 |
---|---|
ScrollView 스크롤 위치 동기화-Android (0) | 2020.08.27 |
Fabric에서 SSH 키 파일 사용 (0) | 2020.08.27 |
jquery / javascript를 통해 추가하는 방법은 무엇입니까? (0) | 2020.08.27 |
mod_rewrite가 서버에서 활성화되었는지 확인하는 방법은 무엇입니까? (0) | 2020.08.27 |