Google Maps Api v3,使用场所库时的动态缩放级别

时间:2013-12-09 21:07:46

标签: javascript jquery google-maps google-maps-api-3

我有一个(相当大的)JSON对象数组,每个数组都包含一个纬度和经度值。当我的Google地图加载时,我遍历此数组并创建一个新标记,该标记将添加到地图中。

除此之外,我正在使用Google Maps Api v3 Places插件(此示例中非常开箱即用:https://developers.google.com/maps/documentation/javascript/examples/places-searchbox

当我搜索给定地址时,我需要确保在地图上至少可以看到N个我的标记。现在,我一直将缩放级别设置为10。但是,当我搜索即法罗群岛(约有5个标记)时,缩放级别太近,用户无法看到5个标记。

有没有办法动态设置缩放级别,以便用户可以看到至少4或5个标记? : - )

我的代码如下:

$(document).ready(function () {
    var map = null;
        var markers = [];
        var overlays = [];

        var infowindow = new google.maps.InfoWindow();

        // Init google map (API v. 3)
        var mapOptions = {
            center: new google.maps.LatLng(56.161, 10.77),
            zoom: 7,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };

        map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

        var marker, i;

        for (i = 0; i < data.length; i++) {
            // Create a new marker
            marker = new google.maps.Marker({
                position: new google.maps.LatLng(data[i].Latitude, data[i].Longitude),
                map: map,
                title: data[i].Name
            });

            // Add the marker to a global array for filtering
            markers.push(marker);
        }

        // Create the search box and link it to the UI element.
        var input = /** @type {HTMLInputElement} */(
            document.getElementById('pac-input'));
        map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

        var searchBox = new google.maps.places.SearchBox(
          /** @type {HTMLInputElement} */(input));

        // [START region_getplaces]
        // Listen for the event fired when the user selects an item from the
        // pick list. Retrieve the matching places for that item.
        google.maps.event.addListener(searchBox, 'places_changed', function () {
            var places = searchBox.getPlaces();

            for (var i = 0, marker; marker = markers[i]; i++) {
                if (markers[i].type == "userMarker") {
                    marker.setMap(null);
                }
            }

            // For each place, get the icon, place name, and location.
            var bounds = new google.maps.LatLngBounds();
                for (var i = 0, place; place = places[i]; i++) {
                var image = {
                    url: place.icon,
                    size: new google.maps.Size(71, 71),
                    origin: new google.maps.Point(0, 0),
                    anchor: new google.maps.Point(17, 34),
                    scaledSize: new google.maps.Size(35, 35)
                };

                // Create a marker for each place.
                var marker = new google.maps.Marker({
                    map: map,
                    icon: image,
                    title: place.name,
                    position: place.geometry.location
                });

                marker.type = "userMarker";
                markers.push(marker);

                bounds.extend(place.geometry.location);                    
            }

            map.fitBounds(bounds);
            map.setZoom(11);
        });
        // [END region_getplaces]

        // Bias the SearchBox results towards places that are within the bounds of the
        // current map's viewport.
        google.maps.event.addListener(map, 'bounds_changed', function () {
            var bounds = map.getBounds();               
            searchBox.setBounds(bounds);
        });
}

提前多多感谢!

1 个答案:

答案 0 :(得分:0)

这是我用来确保在搜索或更改位置等时在地图上着陆时至少可以看到一个标记。它只能确保一个标记在视图中以及用户/搜索查询的当前位置(marker_location) )。

我的标记数组称为mapMarkers [],我认为在查看代码时,您需要将其更新为标记。

它当前找到距离地图中心最近的标记(c),但您可以将其更新为另一个位置。

每当您想要更新时运行setBounds()。

希望您能够扩展它以确保您需要的页面上有许多标记。每个标记距离都存储在distance []数组中,所以也许可以对它进行数组排序,一个for循环并返回一个标记数组并在每个标记上绑定它们?

function rad(x) {return x*Math.PI/180;}

var c = map.getCenter(),
lat = c.lat(),
lng = c.lng();

center_location = new google.maps.LatLng(lat, lng);

function find_closest_marker() {
    var R = 6371; // radius of earth in km
    var distances = [];
    var closest = -1;
    for( i=0; i<mapMarkers.length; i++ ) {
        var mlat = mapMarkers[i].position.lat();
        var mlng = mapMarkers[i].position.lng();
        var dLat  = rad(mlat - lat);
        var dLong = rad(mlng - lng);
        var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
                Math.cos(rad(lat)) * Math.cos(rad(lat)) * Math.sin(dLong/2) * Math.sin(dLong/2);
        var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
        var d = R * c;
        distances[i] = d;
        if ( closest == -1 || d < distances[closest] ) {
                closest = i;
        }
    }

    return mapMarkers[closest];
}

function setBounds(){
    var closestMarker = find_closest_marker();

    var bounds = new google.maps.LatLngBounds();
    bounds.extend(closestMarker.position);
    bounds.extend(center_location); 
    map.fitBounds(bounds);
}