Javascript 如何谷歌地图设置中心/设置缩放并设置边界以包括所有标记

Javascript 如何谷歌地图设置中心/设置缩放并设置边界以包括所有标记,javascript,google-maps,google-maps-api-3,Javascript,Google Maps,Google Maps Api 3,我一直试图从其他帖子中弄明白这一点,但我不能完全理解。以下是我正在使用的代码: <script type="text/javascript"> var mapOptions = { center: new google.maps.LatLng(29.4814305, -98.5144044), zoom: 10 }; var map = new google.maps.Map(document.getElementById("map-canvas"), mapOpt

我一直试图从其他帖子中弄明白这一点,但我不能完全理解。以下是我正在使用的代码:

<script type="text/javascript">
var mapOptions = {
  center: new google.maps.LatLng(29.4814305, -98.5144044),
  zoom: 10
};

var map = new google.maps.Map(document.getElementById("map-canvas"),
    mapOptions);

var markers = [];

// Add a marker to the map and push to the array.
function addMarker(location) {
  var marker = new google.maps.Marker({
    position: location,
    map: map,
    draggable: false,
    animation: google.maps.Animation.DROP
  });

  markers.push(marker);
}

// Sets the map on all markers in the array.
function setAllMap(map) {
  for (var i = 0; i < markers.length; i++) {
        markers[i].setMap(map);
  }
}

// Removes the markers from the map, but keeps them in the array.
function clearMarkers() {
  setAllMap(null);
}

// Deletes all markers in the array by removing references to them.
function deleteMarkers() {
  clearMarkers();
  markers = [];
}

$('#ajax-form').on('submit', function (e) {
    e.preventDefault();
    var formValues = $(this).serialize();
    //console.log('formValues: ' + formValues);

    // Clear previous results if present
    $('#results-list').html('');

    // Send Ajax Request 
    $.ajax({
        url: "/search",
        type: "POST",
        data: formValues,
        dataType: "json",
        success: function (data) {
            // console.log(data);
            var count = 0;

            $(data).each(function() {
                count++;
                // console.log('=========');
                // console.log('Id: ' + this.id);
                // console.log('Breed: ' + this.breed.name);
                // console.log('Dog Name: ' + this.name);
                // console.log('Sex: ' + this.sex);
                // console.log('Age: ' + this.age);
                // console.log('Purebred? ' + this.purebred);
                // console.log('Owner: ' + this.user.username);
                // console.log('=========');
                // console.log(this.user.fullAddress);

                // additional syntax to update html with search results.
                $('#results-list').append(
                    '<div class="row">' +
                        '<div class="col-md-2">' +
                            "<img src=\"" + this.img_path + "\" class=\"img-responsive thumbnail\" >" + 
                        '</div>' +

                        '<div class="zero-margin-left blog-block">' +
                            '<div class="col-md-6">' +
                                '<a href="http://ruff-love.com/dogs/' + this.id + '"><h3>' + this.name + '</a> | ' + '<a href="http://ruff-love.com/users/' + this.user.id + '">' + this.user.username + '</h3></a>' +
                                '</div>' + 
                                '</div>'
                    );

                var address = this.user.fullAddress;
                // console.log(address);

                var geocoder = new google.maps.Geocoder();
                geocoder.geocode({ 'address': address }, function(result, status) {
                    if (status == google.maps.GeocoderStatus.OK) {
                        var latLngObj = result[0]["geometry"]["location"];
                        // add marker to array
                        addMarker(latLngObj);
                    } // endif

                    // COMMENTED OUT NON-WORKING CODE
                    // // map: an instance of GMap3
                    // // latlng: an array of instances of GLatLng
                    // var latlngbounds = new google.maps.LatLngBounds();
                    // markers.each(function(n){
                    //    latlngbounds.extend(n);
                    // });
                    // map.setCenter(latlngbounds.getCenter());
                    // map.fitBounds(latlngbounds);

                }); // end geocode address

            }); // end each data loop

            // Clear previous markers
            deleteMarkers();

            // Add all markers to map
            setAllMap(map);
            // setAllMapTimed(map);

        } // end data function
    }); // end .ajax

}); // end ajax-form block
</script>

变量映射选项={
中心:新google.maps.LatLng(29.4814305,-98.5144044),
缩放:10
};
var map=new google.maps.map(document.getElementById(“地图画布”),
地图选项);
var标记=[];
//将标记添加到地图并推送到阵列。
功能添加标记(位置){
var marker=new google.maps.marker({
位置:位置,,
地图:地图,
可拖动:错误,
动画:google.maps.animation.DROP
});
标记器。推(标记器);
}
//在阵列中的所有标记上设置贴图。
函数setAllMap(映射){
对于(var i=0;i
该视图的全部目的是提供搜索结果,并根据预定义的半径(指定邮政编码内的距离)和其他一些条件在地图上绘制标记

我试图在标记数组填充时,设置地图的边界以包含这些标记,并将缩放设置为某种适当的级别

我知道需要对边界做些什么,只是不知道代码应该放在哪里。我不知道如何计算缩放(查看边界中包含的总距离并相应计算缩放的函数?)


我仍在学习javascript,因此非常感谢您的帮助。谢谢

所以您正在制作一篇AJAX文章来获取一些数据。然后在数据上循环,为每个数据调用
addMarker
函数,并将每个标记添加到数组中。循环完成后,从数组中删除所有标记,然后尝试使用
setAllMap
函数将(现在为空)数组中的所有标记添加到地图上

首先,最初创建标记时,您已经在MarkerOptions属性中设置了贴图:

var marker = new google.maps.Marker({
    position: location,
    map: map,
因此,您不需要在以下情况下再次执行此操作:

markers[i].setMap(map);
其次,我要说的是,在成功处理程序的一开始,在循环处理AJAX请求的结果之前,调用
deleteMarkers

最后,回答你的问题。添加每个标记时,需要扩展地图的“边界”以包括标记

创建一个空边界对象变量,如下所示:

    bounds = new google.maps.LatLngBounds ();
您可能需要以与地图和标记相同的方式将其设置为全局变量

然后在addMarker函数中,添加:

bounds.extend(location);
最后,在循环结束时,您希望将此边界应用于贴图本身:

map.fitBounds(bounds);
总而言之,大概是

<script type="text/javascript">
var mapOptions = {
  center: new google.maps.LatLng(29.4814305, -98.5144044),
  zoom: 10
};

var map = new google.maps.Map(document.getElementById("map-canvas"),
    mapOptions);

var markers = [];
var bounds = new google.maps.LatLngBounds();

// Add a marker to the map and push to the array.
function addMarker(location) {
  var marker = new google.maps.Marker({
    position: location,
    map: map,
    draggable: false,
    animation: google.maps.Animation.DROP
  });

  markers.push(marker);

  bounds.extend(location);
}

// Sets the map on all markers in the array.
function setAllMap(map) {
  for (var i = 0; i < markers.length; i++) {
        markers[i].setMap(map);
  }
}

// Removes the markers from the map, but keeps them in the array.
function clearMarkers() {
  setAllMap(null);
}

// Deletes all markers in the array by removing references to them.
function deleteMarkers() {
  clearMarkers();
  markers = [];
}

$('#ajax-form').on('submit', function (e) {
    e.preventDefault();
    var formValues = $(this).serialize();

    // Clear previous results if present
    $('#results-list').html('');

    // Send Ajax Request 
    $.ajax({
        url: "/search",
        type: "POST",
        data: formValues,
        dataType: "json",
        success: function (data) {
            // Clear previous markers
            deleteMarkers();

            $(data).each(function() {
                // additional syntax to update html with search results.
                $('#results-list').append('...');

                var address = this.user.fullAddress;

                var geocoder = new google.maps.Geocoder();
                geocoder.geocode({ 'address': address }, function(result, status) {
                    if (status == google.maps.GeocoderStatus.OK) {
                        var latLngObj = result[0]["geometry"]["location"];
                        // add marker to array
                        addMarker(latLngObj);
                    } // endif
                }); // end geocode address
            }); // end each data loop

            map.fitBounds(bounds);

        } // end data function
    }); // end .ajax

}); // end ajax-form block
</script>

变量映射选项={
中心:新google.maps.LatLng(29.4814305,-98.5144044),
缩放:10
};
var map=new google.maps.map(document.getElementById(“地图画布”),
地图选项);
var标记=[];
var bounds=new google.maps。