如何使用Google Maps setCenter / setZoom并设置边界以包含所有标记

时间:2014-07-30 04:29:03

标签: 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>

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

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

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

我还在学习javascript,所以任何帮助都表示赞赏。谢谢!

1 个答案:

答案 0 :(得分:5)

所以你正在制作AJAX帖子来获取一些数据。然后循环遍历数据,为每个数据调用addMarker函数,并将每个标记添加到数组中。然后在循环之后删除数组中的所有标记,然后尝试使用setAllMap函数将(现在为空)数组中的所有标记添加到地图上。

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

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

所以你不应该再次这样做:

markers[i].setMap(map);

其次,在您循环查看AJAX请求的结果之前,我说在成功处理程序的最开始时调用deleteMarkers

最后,回答你的问题。添加每个标记时,需要扩展地图的范围&#34;包括标记。

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

    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>