javascript - 如何 Google map setCenter/setZoom 并设置边界以包含所有标记

标签 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"),
    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>

此 View 的重点是提供搜索结果,并根据预定义的半径(指定邮政编码内的距离)和其他一些标准在 map 上绘制标记。

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

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

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

最佳答案

因此,您正在创建一个 AJAX 帖子来获取一些数据。然后,您循环遍历数据,为每个数据调用 addMarker 函数,并将每个标记添加到数组中。循环结束后,您将删除数组中的所有标记,然后尝试使用 setAllMap 函数将数组(现在为空)中的所有标记添加到 map 上。

首先,当您最初创建标记时,您将在 MarkerOptions 属性中设置 map :

var marker = new google.maps.Marker({
    position: location,
    map: map,

因此您不需要在以下位置再次执行此操作:

markers[i].setMap(map);

其次,我建议在成功处理程序的一开始就调用 deleteMarkers,然后再循环 AJAX 请求的结果。

最后,回答一下你的问题。添加每个标记时,您需要扩展 map 的“边界”以包含该标记。

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

    bounds = new google.maps.LatLngBounds ();

您可能需要以与 map 和标记相同的方式将其设为全局变量。

然后在 addMarker 函数中添加:

bounds.extend(location);

最后,在循环结束时,您希望将此边界应用于 map 本身:

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>

关于javascript - 如何 Google map setCenter/setZoom 并设置边界以包含所有标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25028778/

相关文章:

android - 在 Google Maps v2 for Android 中自定义标记上的可点击区域

javascript - ng-click 错误 : [$parse:syntax] Syntax Error: Token 'Object' is unexpected, 期待 []]

安卓 map : My Location Button doesn't work on activity first launch

c# - asp.net中如何调用JS函数

javascript - Firefox 与 Chrome 中的scrollTop() 不同

javascript - 如何使div网格相互忽略

javascript - 如何从 github 引用远程文件路径?

google-maps - 谷歌地图 API V3 "Overview"选项

google-maps-api-3 - 谷歌地图 v3 在 infoWindow 中格式化多行内容

javascript - 从可拖动标记前往新街道和城镇