사용자 선택에 대한 응답으로지도에 좌표 집합을 플롯해야합니다. 그런 상황이 발생하면지도를 이동하여 해당 지점 집합에 초점을 맞추고 싶습니다. 모든 좌표가 포함 된 가장 작은 경계 상자 (LatLngBounds)를 찾으려면 어떻게해야합니까?Google지도 JS API에서 위도/경도 좌표 집합을 포함하는 가장 작은 LatLngBounds를 얻으려면 어떻게해야합니까?
답변
Stack Overflow post which @Crescent Fresh pointed to above (v2 API 사용) 외에도 사용하려는 방법은 LatLngBounds.extend()
입니다. 여기
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps LatLngBounds.extend() Demo</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
</head>
<body>
<div id="map" style="width: 400px; height: 300px;"></div>
<script type="text/javascript">
var map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.TERRAIN
});
var markerBounds = new google.maps.LatLngBounds();
var randomPoint, i;
for (i = 0; i < 10; i++) {
// Generate 10 random points within North East America
randomPoint = new google.maps.LatLng(39.00 + (Math.random() - 0.5) * 20,
-77.00 + (Math.random() - 0.5) * 20);
// Draw a marker for each random point
new google.maps.Marker({
position: randomPoint,
map: map
});
// Extend markerBounds with each random point.
markerBounds.extend(randomPoint);
}
// At the end markerBounds will be the smallest bounding box to contain
// our 10 random points
// Finally we can call the Map.fitBounds() method to set the map to fit
// our markerBounds
map.fitBounds(markerBounds);
</script>
</body>
</html>
스크린 샷 :
.extend()의 문제점은 방향성 때문입니다. 테두리 상자는 커지지 만 축소하지는 않습니다. 따라서 이미 모든 마커가있는 경계 상자를 만든 다음 마커를 제거한 경우 마커를 축소하는 유일한 방법은 모든 마커를 다시 반복하는 것입니다. 이것은 매우 솔직히 저에게 비효율적 인 것처럼 보입니다. 누구든지 새로운 LatLngBounds로 모든 마커를 다시 볼 필요가없는 더 나은 방법을 알고 있습니까? –
@Andrew : 삭제 된 마커가 테두리 상자 테두리에 있는지 쉽게 테스트 할 수 있습니다 ... 따라서 테두리에있는 표식이 삭제 될 때만 테두리 상자를 다시 생성 할 수 있습니다. 국경의 표식이 삭제되는 확률은 낮습니다. 마커가 몇 개 밖에없는 경우에도 작업 속도는 매우 빠릅니다. –
@AndrewDeAndrade 마커가 제거되면 경계를 다시 계산하는 것은 비효율적이지 않습니다. 그들이 제공 한 모든 내장 기능은 아마도 그렇게 할 것입니다. 대안은 배열에 범위를 확장하는 각 단계를 저장하고 제거 할 경우 이전 배열 요소를 참조하는 것입니다. – Frug
참조 http://stackoverflow.com/questions/2362337/how-to-set-the -google-map-zoom-level-depends-to-show-all-the-markers –