2012-02-09 2 views
2

나는 잠시 동안 작업 해 왔고지도 캔버스의 모든 핀을 동적으로 맞추기 위해 latlngbounds를 구현하려고합니다. 그러나 그것은 작동하지 않습니다. 누군가 내 코드와 비슷한 sth을 수행 한 경우 올바른 경로에서 나를 안내 할 수 있습니까?Google API v3지도에 맞게 모든 마커의 확대/축소 범위

var geocoder; 
var map; 
function initializeMap() { 
    geocoder = new google.maps.Geocoder(); 
    var latlng = new google.maps.LatLng(39.88445,-86.11084); 
    var myOptions = { 
     zoom: 9, 
     center: latlng, 
     mapTypeId: google.maps.MapTypeId.ROADMAP 
    }; 
    map = new google.maps.Map(document.getElementById("map_canvas"), 
     myOptions); 
} 
function codeAddress() { 
    var bound = new google.maps.LatLngBounds(); 
    var markers = new Array(); 
    var infowindow = new google.maps.InfoWindow({}); 
    $('.LocAddHidden').each(function(index) { 
     var addy = $(this).text(); 
     geocoder.geocode({ 'address': addy}, function(results, status) { 
      if (status == google.maps.GeocoderStatus.OK) 
      { 
       map.setCenter(results[0].geometry.location); 
       var marker = new google.maps.Marker({ 
       position: results[0].geometry.location, 
       map: map,     
       title:addy  
       });  
      } 
     }); 
    }); 
} 

    $(document).ready(function(){ 
    initializeMap(); 
    codeAddress();  
    for(var i in markers) 
    { 
    bound.extend(markers[i].getPosition()); 
    } 
    map.fitBounds(bound); 
});       
+2

'var bound = new google.maps.LatLngBounds();'이 변수는'codeAddress()'함수의 외부에서 사용할 수없는 LOCAL 변수이다.'bound.extend (marker [i] .getPosition());'마커에 대해서도 마찬가지입니다. – Cheery

답변

2

주된 문제점은 빈 루프에서 범위를 확장한다는 것입니다. 나는 당신이 codeAddress()의 시작 부분에 만드는 마커 배열에 아무 것도 추가하지 않는 것을 보았다. 지오 코드 요청에서 생성 한 마커를 추가해야합니다.

그러나 하나의 루프에서 마커 배열에 추가 한 다음 다른 루프에서 경계를 확장하는 대신 두 번째 루프를 제거하고 첫 번째 루프에서 경계를 확장 할 수 있습니다.

그리고 루프 반복마다 맵을 다시 입력 할 필요가 없습니다. 맨 마지막에 경계를 설정하면 중심을 다시 잡고 확대/축소 할 수 있습니다.

그리고 Cheery는 가변 범위에 대한 또 다른 문제점을 지적했습니다. 대신 사용

+0

고맙습니다. 올바른 방향으로 나를 보내 주셔서 감사합니다! –

0

당신은 당신의 코드에서 마커의 배열을 선언하고, 그 배열 IE8이 작동하려면

// global 
var markers = []; 

// after created 
markers.push(marker); 
3

에 작성된 각 마커를 밀어해야합니다 ..

: for(var i in markersArray)

다음을 사용하십시오 : for (i = 0; i < markersArray.length; i++)

0

여러 번 시도해 본 후에, 저는 간단하고 실용적인 것을 가지고 있습니다 :

function simulateBounds() { 

    var bounds = new google.maps.LatLngBounds; 

    for (var i = 0; i < arrayChinchetas.length; i++) { 
     bounds.extend(arrayChinchetas[i].getPosition()); 
    } 

    SurOeste = bounds.getSouthWest(); 
    NorEste = bounds.getNorthEast(); 

    //Constructs a rectangle from the points at its south-west and north-east corners. 
    var latlandBounds = new google.maps.LatLngBounds(SurOeste, NorEste); 

    map.fitBounds(latlandBounds); 

} 
관련 문제