programing

Google Maps API v3: fitBounds 후 줌을 설정할 수 있습니까?

goodjava 2022. 11. 5. 17:47

Google Maps API v3: fitBounds 후 줌을 설정할 수 있습니까?

내장된 Google 지도(API v3)에 표시할 포인트 세트가 있습니다.확대/축소 수준이 너무 낮지 않은 경우(예: 너무 축소됨) 경계가 모든 점을 수용하도록 합니다.저의 접근 방식은 다음과 같습니다.

var bounds = new google.maps.LatLngBounds();

// extend bounds with each point

gmap.fitBounds(bounds); 
gmap.setZoom( Math.max(6, gmap.getZoom()) );

이거 안 되네.마지막 줄 "gmap"setZoom()은 fitBounds 직후에 호출해도 맵의 줌 레벨을 변경하지 않습니다.

지도에 적용하지 않고 바운드의 줌 레벨을 얻을 수 있는 방법이 있나요?이 문제를 해결하기 위한 다른 아이디어는?

편집: 아래 Matt Diamond의 코멘트를 참조하십시오.

알았어! 이거 먹어봐:

map.fitBounds(bounds);
var listener = google.maps.event.addListener(map, "idle", function() { 
  if (map.getZoom() > 16) map.setZoom(16); 
  google.maps.event.removeListener(listener); 
});

필요에 따라 수정합니다.

나는 내 앱 중 하나에서 비슷한 문제를 해결했다.문제에 대한 당신의 설명에 조금 혼란스러웠지만, 제 생각에 당신은 저와 같은 목표를 가지고 있는 것 같아요.

내 앱에서 하나 이상의 마커를 표시하고 지도에 모든 마커가 표시되어 있는지 확인하고 싶었다.문제는 fitBounds 방식에만 의존하면 싱글포인트가 있을 때 줌레벨이 최대가 될 수 있다는 것입니다.

이 솔루션은 포인트가 많을 때는 fitBounds를 사용하고 포인트가 하나밖에 없을 때는 Center+setZoom을 설정하는 것이었습니다.

if (pointCount > 1) {
  map.fitBounds(mapBounds);
}
else if (pointCount == 1) {
  map.setCenter(mapBounds.getCenter());
  map.setZoom(14);
}

저는 답을 얻기 위해 이 페이지를 여러 번 방문했고, 기존의 답변들은 모두 큰 도움이 되었지만, 제 문제를 정확히 해결하지는 못했습니다.

google.maps.event.addListenerOnce(googleMap, 'zoom_changed', function() {
    var oldZoom = googleMap.getZoom();
    googleMap.setZoom(oldZoom - 1); //Or whatever
});

기본적으로 'zoom_changed' 이벤트 때문에 맵의 UI가 '스킵'되지 않았습니다.아이돌' 이벤트를 기다릴 때 발생하였습니다.

이게 도움이 됐으면 좋겠네요!

max Zoom을 미리 설정하고 나중에 삭제하여 수정했습니다.예를 들어 다음과 같습니다.

map.setOptions({ maxZoom: 15 });
map.fitBounds(bounds);
map.setOptions({ maxZoom: null });

다음을 시도해 보십시오.

map.fitBounds(bounds);

// CHANGE ZOOM LEVEL AFTER FITBOUNDS
zoomChangeBoundsListener = google.maps.event.addListenerOnce(map, 'bounds_changed', function(event) {
  if (this.getZoom()){
    this.setZoom(15);
  }
});
setTimeout(function(){
  google.maps.event.removeListener(zoomChangeBoundsListener)
}, 2000);

내가 틀리지 않았다면, 당신은 지도에서 가능한 한 높은 줌 레벨로 모든 점을 볼 수 있기를 원할 것입니다.이것을 실현하려면 , 지도의 레벨을 16으로 초기화했습니다(V3의 줌 레벨이 가장 높은지는 불명).

var map = new google.maps.Map(document.getElementById('map_canvas'), {
  zoom: 16,
  center: marker_point,
  mapTypeId: google.maps.MapTypeId.ROADMAP
});

그 후엔 경계 같은 걸 했죠

var bounds = new google.maps.LatLngBounds();

// You can have a loop here of all you marker points
// Begin loop
bounds.extend(marker_point);
// End loop

map.fitBounds(bounds);

결과: 성공!

부정확하거나 너무 복잡한 해결책을 많이 봤기 때문에 효과적이고 우아한 해결책을 올리기로 했습니다.

★★setZoom()fitBounds() 갱신되는 , 은 「」입니다.setZoom()거기에 의존합니다.

생각해도 좋을 이다, 설정하다, 설정하다.minZoom콜 전)fitBounds()완료 후 클리어합니다(사용자가 원할 경우 수동으로 축소할 수 있습니다).

var bounds = new google.maps.LatLngBounds();
// ... (extend bounds with all points you want to fit)

// Ensure the map does not get too zoomed out when fitting the bounds.
gmap.setOptions({minZoom: 6});
// Clear the minZoom only after the map fits the bounds (note that
// fitBounds() is asynchronous). The 'idle' event fires when the map
// becomes idle after panning or zooming.
google.maps.event.addListenerOnce(gmap, 'idle', function() {
  gmap.setOptions({minZoom: null});
});

gmap.fitBounds(bounds);

을 제한하고 는, ,, 최, 최, 은, 은, 은, 은, 은, 은, 은, 은, 은, 은, 은, 은, 은, 은, 은, 은, 은, 은, with, with, with, with, with, with, with, with, with, with, , with, with, with, maxZoom★★★★★★★★★★★★★★★★★★.

MapOptions 문서를 참조하십시오.

사용방법:

gmap.setZoom(24); //this looks a high enough zoom value
gmap.fitBounds(bounds); //now the fitBounds should make the zoom value only less

이것은 코드에 따라 24개 중 작은 것과 필요한 확대/축소 수준을 사용하지만, 축소를 얼마나 했는지는 신경 쓰지 않습니다.

저도 같은 문제가 있어서 아래의 코드를 사용하여 해결할 수 있었습니다.리스너(「」)google.maps.addListenerOnce()하며, 그 합니다.map.fitBounds() 그럴 는 없어요.

  1. 청취자를 추적하여 수동으로 삭제합니다.또는
  2. 맵이 표시될 때까지 기다립니다.idle.

처음에는 적절한 확대/축소 레벨을 설정하고 이벤트청취자가 만료되었기 때문에 사용자가 초기 확대/축소 레벨을 초과하여 확대/축소할 수 있습니다.를 들어, ''만 있는 ,google.maps.addListener()가 호출되면 사용자는 지정된 줌 레벨(이 경우 4)을 초과하여 줌인할 수 없습니다.도입 후google.maps.addListenerOnce()사용자는 원하는 레벨로 줌할 수 있습니다.

map.fitBounds(bounds);

var zoom_level_for_one_marker = 4;

google.maps.event.addListenerOnce(map, 'bounds_changed', function(event){
   if (this.getZoom() >= zoom_level_for_one_marker){  
       this.setZoom(zoom_level_for_one_marker) 
   }
});

같은 문제가 있어서 지도에 많은 표식을 넣어야 했다.이것으로 제 문제는 해결되었습니다.

  1. 경계를 선언하다
  2. 각 마커 세트에 " 사용)bounds.extend(objLatLng))
  3. 맵이 완료된 후 핏바운드를 실행합니다.

    google.maps.event.addListenerOnce(map, 'idle', function() { 
        map.fitBounds( bounds );
    });
    

fitBounds 갑자기 줌인하다

var bounds = new google.maps.LatLngBounds();

// extend bounds with each point

var minLatSpan = 0.001;
if (bounds.toSpan().lat() > minLatSpan) {
    gmap.fitBounds(bounds); 
} else {
    gmap.setCenter(bounds.getCenter());
    gmap.setZoom(16);
}

원하는 위치에 도달하려면 minLatSpan 변수를 좀 더 활용해야 합니다.확대/축소 수준과 지도 캔버스의 치수에 따라 달라집니다.

위도 대신 경도를 사용할 수도 있습니다.

위성 이미지를 사용할 수 있도록 줌 레벨이 설정 레벨을 넘지 않도록 하기 위해 사용합니다.

를 추가하세요.zoom_changed이벤트. UI에서 확대/축소 컨트롤을 제어하는 이점도 있습니다.

" "만 "setZoom, an면면, 면 if if ififMath.max 「」로Math.min

   google.maps.event.addListener(map, 'zoom_changed', function() { 
      if ( map.getZoom() > 19 ) { 
        map.setZoom(19); 
      } 
    });
    bounds = new google.maps.LatLngBounds( ... your bounds ... )
    map.fitBounds(bounds);

너무 멀리 축소되지 않도록 하려면:

   google.maps.event.addListener(map, 'zoom_changed', function() { 
      if ( map.getZoom() < 6 ) { 
        map.setZoom(6); 
      } 
    });
    bounds = new google.maps.LatLngBounds( ... your bounds ... )
    map.fitBounds(bounds);

이 함수에서는 함수에서 모든 지오메트리를 받아들이기 때문에 지오메트리 유형만 저장하기 위해 메타데이터를 동적으로 추가해야 합니다.

"피트 지오메트리"는 지도 객체를 확장하는 JSON 함수입니다.

"geometries"는 MVCAray()가 아닌 일반적인 javascript 배열입니다.

geometry.metadata = { type: "point" };
var geometries = [geometry];

fitGeometries: function (geometries) {
    // go and determine the latLngBounds...
    var bounds = new google.maps.LatLngBounds();
    for (var i = 0; i < geometries.length; i++) {
        var geometry = geometries[i];
        switch (geometry.metadata.type)
        {
            case "point":
                var point = geometry.getPosition();
                bounds.extend(point);
                break;
            case "polyline":
            case "polygon": // Will only get first path
                var path = geometry.getPath();
                for (var j = 0; j < path.getLength(); j++) {
                    var point = path.getAt(j);
                    bounds.extend(point);
                }
                break;
        }
    }
    this.getMap().fitBounds(bounds);
},

이 작업은 API v3를 사용하지만 고정 줌을 설정한 경우:

var bounds = new google.maps.LatLngBounds();
// extend bounds with each point

gmap.setCenter(bounds.getCenter()); 
gmap.setZoom( 6 );

나처럼 청취자와 함께 놀고 싶지 않은 경우, 내가 생각해낸 간단한 해결책은 다음과 같습니다. 다음과 같이 요구 사항에 따라 엄격하게 동작하는 방법을 지도에 추가합니다.

    map.fitLmtdBounds = function(bounds, min, max){
        if(bounds.isEmpty()) return;
        if(typeof min == "undefined") min = 5;
        if(typeof max == "undefined") max = 15;

        var tMin = this.minZoom, tMax = this.maxZoom;
        this.setOptions({minZoom:min, maxZoom:max});
        this.fitBounds(bounds);
        this.setOptions({minZoom:tMin, maxZoom:tMax});
    }

그럼 대신 전화해 주세요.map.fitBounds(bounds)정의된 확대/축소 범위에서 경계를 설정하려면...또는 확대/축소 범위를 재정의합니다.

이거 드셔보세요.

// Find out what the map's zoom level is
zoom = map.getZoom();
if (zoom == 1) {
  // If the zoom level is that low, means it's looking around the
world.
  // Swap the sw and ne coords
  viewportBounds = new
google.maps.LatLngBounds(results[0].geometry.location, initialLatLng);
  map.fitBounds(viewportBounds);
}

이것이 당신에게 도움이 된다면.

행운을 빌어요.

경계를 계산한 후 왼쪽 위 모서리와 오른쪽 아래 모서리 사이의 거리를 확인할 수 있습니다. 그런 다음 거리를 테스트하여 줌 레벨을 이해할 수 있습니다(거리가 너무 먼 경우 줌 레벨이 낮습니다). 그런 다음 setbound 방법 또는 setZoom을 사용하여 휠터를 선택할 수 있습니다.

제안하고 싶지는 않지만, 꼭 시도해 봐야 한다면 - 첫 번째 전화

gmap.fitBounds(bounds);

그런 다음 새로운 스레드/비동기 태스크를 생성하여 20~50밀리초 정도 sleeve 상태로 둔 후 호출합니다.

gmap.setZoom( Math.max(6, gmap.getZoom()) );

(핸들러 또는 를 사용하여)onPostExecute메서드)를 참조해 주세요).

효과가 있을지는 모르겠지만, 그냥 제안일 뿐이에요.그 외에는 직접 포인트에서 줌 레벨을 계산하여 너무 낮지 않은지 확인하고 수정한 후 전화를 걸어야 합니다.gmap.setZoom(correctedZoom)

bounds_changed'가 올바르게 실행되지 않는 경우(때로는 Google이 좌표를 완벽하게 받아들이지 않는 것 같음), 대신 'center_changed'를 사용하는 것을 고려해 보십시오.

'center_changed' 이벤트는 fitBounds()가 호출될 때마다 실행됩니다.단, 맵이 이동한 후에는 즉시 실행되지 않습니다.

일반적인 경우 'idle'은 여전히 최고의 이벤트 리스너이지만 fitBounds() 호출에서 이상한 문제에 부딪히는 커플에게 도움이 될 수 있습니다.

구글fitBounds 콜백 참조

다른 솔루션과 보조를 맞추는 방법 - "listen for bounds_changed events and set new zoom" 접근법이 나에게 확실하게 작동하지 않는다는 것을 알게 되었습니다.내가 가끔 전화했던 것 같아fitBounds맵이 완전히 초기화되기 전에, 그리고 초기화로 인해 리스너를 소비하는 bounds_displays 이벤트가 발생하고 있었습니다.fitBounds경계 및 확대/축소 수준을 변경했습니다.는 이 것 .- 국결 、 금국 、 금 i 、 i i i i,,, i i 。

// If there's only one marker, or if the markers are all super close together,
// `fitBounds` can zoom in too far. We want to limit the maximum zoom it can
// use.
//
// `fitBounds` is asynchronous, so we need to wait until the bounds have
// changed before we know what the new zoom is, using an event handler.
//
// Sometimes this handler gets triggered by a different event, before
// `fitBounds` takes effect; that particularly seems to happen if the map
// hasn't been fully initialized yet. So we don't immediately remove the
// listener; instead, we wait until the 'idle' event, and remove it then.
//
// But 'idle' might happen before 'bounds_changed', so we can't set up the
// removal handler immediately. Set it up in the first event handler.

var removeListener = null;
var listener = google.maps.event.addListener(map, 'bounds_changed', () => {
  console.log(map.getZoom());
  if (map.getZoom() > 15) {
    map.setZoom(15);
  }

  if (!removeListener) {
    removeListener = google.maps.event.addListenerOnce(map, 'idle', () => {
      console.log('remove');
      google.maps.event.removeListener(listener);
    });
  }
});

저에게 가장 쉬운 해결책은 다음과 같습니다.

map.fitBounds(bounds);

function set_zoom() {
    if(map.getZoom()) {map.setZoom(map.getZoom() - 1);}
    else {setTimeout(set_zoom, 5);}
}
setTimeout(set_zoom, 5);
google.maps.event.addListener(marker, 'dblclick', function () {
    var oldZoom = map.getZoom(); 
    map.setCenter(this.getPosition());
    map.setZoom(parseInt(oldZoom) + 1);
});

제가 한 건

map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));

V3 API에서도 동작합니다.

언급URL : https://stackoverflow.com/questions/2437683/google-maps-api-v3-can-i-setzoom-after-fitbounds