使用GeoJson GoogleMaps Api v3缩放到标记

时间:2014-05-06 07:26:55

标签: javascript google-maps-api-3 viewport geojson bounding

我正在尝试将我的视图设置为我加载的geojson数据。任何提示?

到目前为止,这是我的代码:

<script>
//Load Map
    var map;
    function initialize() {
      map = new google.maps.Map(document.getElementById('map-canvas'), {
        center: new google.maps.LatLng(0, 0),
        zoom: 2
        });
        map.data.loadGeoJson('Points.geojson');
    }
    google.maps.event.addDomListener(window, 'load', initialize);

//Json to Array
var myMarkers;
    $.getJSON('Points.geojson')
    .done(function (data) {
    myMarkers = data;
    });
</script>

正如你所看到的,我已经在一个数组中加载了Json - 但我不确定如何获得这些边界。在我的搜索过程中,我总是来到这个页面:http://blog.shamess.info/2009/09/29/zoom-to-fit-all-markers-on-google-maps-api-v3/但不幸的是我刚刚开始使用Javascript而我无法修改我的代码。

这就是我的Geojson的样子:

{
    "type": "FeatureCollection",
    "features": [{
        "type": "Feature",
        "properties": {
            "Name": "SiteA",
            "Adresse": "Adress1",
            "Hausnummer": 1,
            "Postleitzahl": 1000,
            "Ort": "Here",
            "Long": 10,
            "Lat": 50
        },
        "geometry": {
            "type": "Point",
            "coordinates": [10, 50]
        }
    }, {
        "type": "Feature",
        "properties": {
            "Name": "SiteB",
            "Adresse": "Adress2:",
            "Hausnummer": 2,
            "Postleitzahl": 1001,
            "Ort": "There",
            "Long": 5,
            "Lat": 60
        },
        "geometry": {
            "type": "Point",
            "coordinates": [5, 60]
        }
    }]
}

提前致谢!

1 个答案:

答案 0 :(得分:4)

你有三分,所以在一个独家新闻中你将它们扩展到LatLngBounds like here然后尝试fitbounds

var bounds = new google.maps.LatLngBounds();


for (var i = 0; i < data.features.length; ii++) {
            a = data.features[i].geometry.coordinates[0];
            b = data.features[i].geometry.coordinates[1];
            point = new google.maps.LatLng(a, b);
            bounds.extend(point);
        }


map.fitBounds(bounds)