2012-01-23 3 views
1

Я хочу, чтобы привязывающие кнопки были видимыми во всех местах расположения пользователя. я написал следующий код, он центрирует местоположение пользователя, но несколько кнопок выходят из карты?Javascript Google map api V3 fitbounds с центральным расположением

FYI: userPinLoc является канцелярской объект, который уже заселен

function setInitialZoom() { 
      mapZoom = googleMap.getZoom(); 
      var bounds = new google.maps.LatLngBounds(); 
      bounds.extend(userPinLoc); 
      for (i in nearestEntitiesToZoom) { 
       entity = nearestEntitiesToZoom[i]; 
       var googleLatLng = new google.maps.LatLng(entity.latitude,entity.longitude); 
       bounds.extend(googleLatLng); 
      } 

      google.maps.event.addDomListener(googleMap, 'bounds_changed', function() { 
       googleMap.setCenter(userPinLoc); 
      }); 
       googleMap.fitBounds(bounds); 
     } 

ответ

0

Я сделал это с помощью Java и JavaScript

public static void calculateMapFitBounds(GeoLocation userLocation, List<GeoLocation> contents, Map<String, GeoLocation> latlngBounds){ 

    if (Util.isEmtpyGeoLocation(userLocation) || contents == null || contents.isEmpty()) { 
     return; 
    } 

    //SW 
    double minLat = userLocation.getLatitude(); 
    double minLng = userLocation.getLongitude(); 

    //NE 
    double maxLat = userLocation.getLatitude(); 
    double maxLng = userLocation.getLongitude(); 

    for(GeoLocation content: contents){ 

     /* 
     * Populating Top left cordinate (SW) 
     */ 
     minLat = Math.min(minLat, content.getLatitude()); 
     minLng = Math.min(minLng, content.getLongitude()); 

     /* 
     * Populating Bottom right cordinate (NE) 
     */ 
     maxLng = Math.max(maxLng, content.getLongitude()) ; 
     maxLat = Math.max(maxLat, content.getLatitude()); 
    } 

    /* 
    * Calculating Delta fit bounds 
    */ 

    double latDelta = Math.max(Math.abs(userLocation.getLatitude() - minLat), Math.abs(maxLat-userLocation.getLatitude())); 

    double lngDelta = Math.max(Math.abs(userLocation.getLongitude() - maxLng), Math.abs(minLng - userLocation.getLongitude())); 

    //Calculating SW 
    minLat = userLocation.getLatitude() - latDelta; 
    minLng = userLocation.getLongitude()- lngDelta; 


    latlngBounds.put("swLatLng", new GeoLocation(minLat, minLng)); 


    //Calculating NE 
    maxLat = userLocation.getLatitude() + latDelta; 
    maxLng = userLocation.getLongitude()+ lngDelta; 

    latlngBounds.put("neLatLng", new GeoLocation(maxLat, maxLng)); 

} 

Я использую вид на скорости, так вот скорость и JS код

#if($swLatLng && $neLatLng) 
     var swLatLn = new google.maps.LatLng($!swLatLng.latitude, $!swLatLng.longitude, false); 
     var neLatLn = new google.maps.LatLng($neLatLng.latitude, $neLatLng.longitude, false); 

     var bounds = new google.maps.LatLngBounds(swLatLn, neLatLn); 
     googleMap.fitBounds(bounds); 

     #end 
0

Я не уверен, где вы получаете userPinLoc от. Дайте этому идти:

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

// Go through each... 
for (i in nearestEntitiesToZoom) { 
    entity = nearestEntitiesToZoom[i]; 
    var googleLatLng = new google.maps.LatLng(entity.latitude, entity.longitude); 
    bounds.extend(googleLatLng); 
}; 

// Fit these bounds to the map 
googleMap.fitBounds(bounds); 
... 

Помните, fitCenter или fitBounds нужен LatLng объект в качестве параметра.

Этот код адаптирован из: http://you.arenot.me/2010/06/29/google-maps-api-v3-0-multiple-markers-multiple-infowindows/

+0

Извините забыть, я уже имея «GoogleMap. fitBounds (Bounds);» эта строка в моей реализации, я не вижу никаких изменений, кроме того, что в вашем коде. –

+0

Мой плохой. Я начал это сообщение, прежде чем вы внесли свою последнюю ревизию на свой вопрос (у нее не было последней 'googleMap.fitBounds (bounds);' line) – ninty9notout

0

Когда я сделал это раньше, я сделал bounds.extend() для отображения центра как самого последнего, а не первого. По какой-то причине казалось, что они работают лучше.

function initialize() { 
    var points = [ 
     { 
      lat: 51.498725, 
      lng: -0.17312 
     }, 
     { 
      lat: 51.4754091676, 
      lng: -0.186810493469 
     }, 
     { 
      lat: 51.4996066187, 
      lng: -0.113682746887 
     }, 
     { 
      lat: 51.51531272, 
      lng: -0.176296234131 
     } 
    ]; 

    var centerLatLng = {lat: 51.532315, lng: -0.1544}; 

    var map = new google.maps.Map(document.getElementById("map"), { 
     zoom:    15, 
     center:    centerLatLng, 
     mapTypeId:   google.maps.MapTypeId.ROADMAP 
    }); 

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

    var homeMarker = new google.maps.Marker({ 
     position: centerLatLng, 
     map: map, 
     icon: "http://maps.google.com/mapfiles/ms/micons/green-dot.png" 
    }); 

    for (var i = 0; i < points.length; i++) {  
     var marker = new google.maps.Marker({ 
      position: points[i], 
      map: map 
     }); 

     bounds.extend(points[i]); 
    } 

    bounds.extend(centerLatLng); 

    map.fitBounds(bounds); 
} 
+0

, делая то же самое, расширяя границы, затем добавляя центральное расположение как привязанное, а затем ограничивая соответствие. Уверен, что он будет на 100% результирующим, чтобы центрировать штырь, окруженный другими штифтами, с идеальной подгонкой? –