【问题标题】:How do I auto zoom to view multiple markers using the Google Geocoding API?如何使用 Google Geocoding API 自动缩放以查看多个标记?
【发布时间】:2019-11-12 15:19:15
【问题描述】:

我正在使用 Google 地理编码 API 构建地图,将标记放置在请求的任何位置上。目前它分别自动缩放到每个位置 - 我如何使用 fit Bounds 使其缩放到所有位置,即如果先输入悉尼,然后输入伦敦,我如何要求它自动缩放以便用户可以两个都看?

我对此很陌生,所以欢迎任何建议!

我尝试了许多不同的方式来使用边界、拟合边界、marker.length 等,但没有一个对我有用或没有多大意义。

function initMap() {
    var map = new google.maps.Map(document.getElementById('map'), {
        center: {lat: 45.1497, lng: 100.0943},
        zoom: 3
    });

    var geocoder = new google.maps.Geocoder()

    var step1 = location.href.split("?")[1].split("=")[1]
    $("#address1").val(step1);
    geocodeAddress1(geocoder, map);

    $(".steps").keypress(function() {
        if (event.which == 13) {
            geocodeAddress(geocoder, map);
        }
    })
};

var labelIndex = 0;

function geocodeAddress1(geocoder, resultsMap) {
    var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

    var address = $("#address1").val();
        geocoder.geocode({'address': address}, function(results, status) {
        if (status === 'OK') {
            resultsMap.setCenter(results[0].geometry.location);
            var marker = new google.maps.Marker({
                map: resultsMap,
                label: labels[labelIndex++ % labels.length],
                position: results[0].geometry.location
            });
        } else {
            alert('Search not successful: ' + status);
            }
        })
};

function geocodeAddress(geocoder, resultsMap) {
    var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    var nextstep = "#".concat(event.target.id);
    debugger;
    var address = $(nextstep).val();
        geocoder.geocode({'address': address}, function(results, status) {
        if (status === 'OK') {
            resultsMap.setCenter(results[0].geometry.location);
            var marker = new google.maps.Marker({
                map: resultsMap,
                label: labels[labelIndex++ % labels.length],
                position: results[0].geometry.location
            });
        } else {
            alert('Search not successful: ' + status);
            }
        })
};

【问题讨论】:

    标签: google-maps-api-3 geocoding google-geocoding-api


    【解决方案1】:

    每次单击“地理编码”时,您需要先将所有标记/位置存储在一个数组中,然后为每个搜索到的包含给定点的位置调用 bounds.extend(),最后调用 resultsMap.fitBounds() 将视口设置为包含给定的边界。

    var marker = new google.maps.Marker({
        map: resultsMap,
        position: results[0].geometry.location
    });
    
    markerCount++;
    markers[markerCount] = marker;
    
    // extend the bounds here to consider each location
    bounds.extend(results[0].geometry.location);
    // then call fitBounts()
    resultsMap.fitBounds(bounds);
    

    这是一个有效的sample in JSFiddle。

    希望对你有帮助!

    【讨论】:

      猜你喜欢
      • 2022-12-03
      • 1970-01-01
      • 2012-11-16
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      • 2020-07-15
      • 1970-01-01
      • 2012-11-01
      相关资源
      最近更新 更多