20

Nell'API v2, l'oggetto della mappa aveva un metodo pratico getBoundsZoomLevel(). L'ho usato per ottenere il livello di zoom che si adatta meglio ai limiti, quindi ho manipolato questo livello di zoom ottimale in qualche modo e infine impostato il livello di zoom desiderato.Equivalente di getBoundsZoomLevel() in gmaps api 3

Non riesco a trovare una funzione simile in API v3. (Che esperienza frustrante continua quando ci si sposta dalla v2 alla v3)

Devo davvero usare map.fitBounds(), map.getZoom(), manipolare e setZoom() di nuovo? È davvero stupido!

+2

un'occhiata a http://stackoverflow.com/questions/6048975/google-maps-v3-how-to-calculate-the-zoom- level-for-a-bounds –

+0

Grazie @ Dr.Molle. È un peccato che tu debba scrivere la tua funzione per questo, quindi in questo caso ho preferito la stupida soluzione che ho presentato sopra. Ma userò il tuo link per [un altro problema] (http://stackoverflow.com/questions/9843732/how-to-affect-the-grace-margin-of-map-fitbounds), grazie !! – TMS

+0

+1 - Sono sorpreso che tu non abbia ricevuto più voti positivi. –

risposta

27

Qui di seguito è una funzione che ho implementato:

/** 
* Returns the zoom level at which the given rectangular region fits in the map view. 
* The zoom level is computed for the currently selected map type. 
* @param {google.maps.Map} map 
* @param {google.maps.LatLngBounds} bounds 
* @return {Number} zoom level 
**/ 
function getZoomByBounds(map, bounds){ 
    var MAX_ZOOM = map.mapTypes.get(map.getMapTypeId()).maxZoom || 21 ; 
    var MIN_ZOOM = map.mapTypes.get(map.getMapTypeId()).minZoom || 0 ; 

    var ne= map.getProjection().fromLatLngToPoint(bounds.getNorthEast()); 
    var sw= map.getProjection().fromLatLngToPoint(bounds.getSouthWest()); 

    var worldCoordWidth = Math.abs(ne.x-sw.x); 
    var worldCoordHeight = Math.abs(ne.y-sw.y); 

    //Fit padding in pixels 
    var FIT_PAD = 40; 

    for(var zoom = MAX_ZOOM; zoom >= MIN_ZOOM; --zoom){ 
     if(worldCoordWidth*(1<<zoom)+2*FIT_PAD < $(map.getDiv()).width() && 
      worldCoordHeight*(1<<zoom)+2*FIT_PAD < $(map.getDiv()).height()) 
      return zoom; 
    } 
    return 0; 
} 
+0

Grazie! Il tuo codice produce gli stessi valori del vecchio v2 getZoomByBounds –

+0

+1 Ottimo lavoro ... funziona bene. TY –

+0

@Engineer hat off – Jaykishan

Problemi correlati