2010-03-22 4 views
31

Google API v3의 지오 코더를 사용하여 국가의지도를 표시하고 있습니다. 국가에 권장 된 뷰포트가 있지만이 뷰포트에 맵을 맞추려면 작동하지 않습니다 (아래 코드에서 fitBounds 함수를 호출하기 전과 후의 경계 참조).Google지도에서 fitbounds()가 경계에 맞지 않습니다.

내가 뭘 잘못하고 있니?

지도의 뷰포트를 results[0].geometry.viewport으로 어떻게 설정할 수 있습니까? fitBounds() 가능한 최대 줌 레벨을 사용하여지도 캔버스에 맞는 뷰포트에 스냅해야하기 때문에

var geocoder = new google.maps.Geocoder(); 
geocoder.geocode(
    {'address': '{{countrycode}}'}, 
    function(results, status) { 
     var bounds = new google.maps.LatLngBounds(); 
     bounds = results[0].geometry.viewport; 
     console.log(bounds);   // ((35.173, -12.524), (45.244, 5.098)) 
     console.log(map.getBounds()); // ((34.628, -14.683), (58.283, 27.503)) 
     map.fitBounds(bounds);    
     console.log(map.getBounds()); // ((25.740, -24.806), (52.442, 17.380)) 
    } 
); 

답변

72

이 발생합니다. 반면에 지오 코더가 반환 한 뷰포트는지도 캔버스의 크기, 레이아웃 또는 확대/축소 수준에 종속되지 않습니다. 따라서 fitBounds() 메서드는 전달 된 LatLngBounds을지도의 중앙에 전체적으로 표시하기 위해지도의 뷰포트를 조정합니다.

당신은 명확하게 시범을 위해 다음의 예를 확인 할 수 있습니다

:

<!DOCTYPE html> 
<html> 
<head> 
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
    <title>Google Maps fitBounds Demo</title> 
    <script src="http://maps.google.com/maps/api/js?sensor=false" 
      type="text/javascript"></script> 
</head> 
<body> 
    <div id="map" style="width: 500px; height: 350px"></div> 

    <script type="text/javascript"> 
     var myOptions = { mapTypeId: google.maps.MapTypeId.ROADMAP }; 
     var map = new google.maps.Map(document.getElementById("map"), myOptions); 
     var geocoder = new google.maps.Geocoder(); 

     geocoder.geocode({'address': 'RU'}, function (results, status) { 
     var ne = results[0].geometry.viewport.getNorthEast(); 
     var sw = results[0].geometry.viewport.getSouthWest(); 

     map.fitBounds(results[0].geometry.viewport);    

     var boundingBoxPoints = [ 
      ne, new google.maps.LatLng(ne.lat(), sw.lng()), 
      sw, new google.maps.LatLng(sw.lat(), ne.lng()), ne 
     ]; 

     var boundingBox = new google.maps.Polyline({ 
      path: boundingBoxPoints, 
      strokeColor: '#FF0000', 
      strokeOpacity: 1.0, 
      strokeWeight: 2 
     }); 

     boundingBox.setMap(map); 
     }); 
    </script> 
</body> 
</html> 

다음은 위의 예에서 여러 나라에 대한 스크린 샷입니다. 빨간색 경계 상자는 지오 코더에서 반환 한 뷰포트입니다.

국가 : 미국

US

국가 : RU

RU

국가 : fitBounds() 조정으로, 경계 상자와 실제 뷰포트의 차이를 참고 IT를

IT

+0

Daniel 감사합니다. – jul

+0

나는 이것도하는 방법을 이해하는 데 어려움을 겪었다, 굉장한 상세한 설명! – designermonkey

+0

철저한 설명에 감사드립니다. boundingBox는이를 명확하게하는 데 좋은 아이디어였습니다. – Symmetric

2

그냥 당신이 어떤 방법이가, 내가 방금 fitBounds

  • 샘플 뷰포트에서 BoundingBox의 일부를 풀어 선호하는 경우에 당신이 할 수있는 일의 샘플을 준비했습니다 사용자 정의 할 수 있습니다 알려합니다 : http://jsbin.com/cakuhaca/1/edit

  • 당신이 더 많은 수준의 모든 뷰포트가 표시되도록 신경 항상 하나의 확대하지 않는 경우에 대한 샘플 : 당신은 일의 경우에만 STIP 신경 때 http://jsbin.com/rofupidi/1/edit

  • 샘플을 테두리가없는 상자는 가로 또는 세로로 X 픽셀 이상입니다. http://jsbin.com/rezapuye/1/edit

+1

:(이 링크는 죽었습니다. –

+2

더 영구 링크로 고정 – kaskader

+4

죽었습니다 ..... –

관련 문제