zoom to geojson polygons bounds in Google Maps API v3

一世执手 提交于 2019-11-27 13:43:13

问题


I'm loading geojson from a Postgis-database and want to display it on my map. After drawing a polygon, I want the map to zoom to the extents of the added polygon.

My data loads fine and displays correct on the map, but I cannot figure out how to get the bounds and change the zoom to the newly added polygon. I tried to use parts of the code from Google's Data Layer: Drag and Drop GeoJSON example, but the displayed map zooms in somewhere in the Pacific Ocean close to the Baker Islands, while the polygon is displayed correctly in Luxembourg.

Here the code I am using:

window.addEventListener("load", func1);

function func1(){
  //Load mapdata via geoJson
  var parzelle = new google.maps.Data();
  parzelle.loadGeoJson("./mapdata/get_parzelle_geojson.php<?php echo  "?gid=".$_GET['gid'];?>");

  // Set the stroke width, and fill color for each polygon
  var featureStyle = {
    fillColor: '#ADFF2F',
    fillOpacity: 0.1,
    strokeColor: '#ADFF2F',
    strokeWeight: 1
  }

  parzelle.setStyle(featureStyle);
  parzelle.setMap(map);

  zoom(map);
}

function zoom(map) {
  var bounds = new google.maps.LatLngBounds();
  map.data.forEach(function(feature) {
    processPoints(feature.getGeometry(), bounds.extend, bounds);
  });
  map.fitBounds(bounds);
}

function processPoints(geometry, callback, thisArg) {
  if (geometry instanceof google.maps.LatLng) {
    callback.call(thisArg, geometry);
  } else if (geometry instanceof google.maps.Data.Point) {
    callback.call(thisArg, geometry.get());
  } else {
    geometry.getArray().forEach(function(g) {
      processPoints(g, callback, thisArg);
    });
  }
}

Is there a way to get that to work? It seems that there is no simple method to get the bounds of polygons in google.maps.data-layers.


回答1:


There are issues with your posted code. You can use map.data to access the data layer.

Working code snippet. Initially zooms to all the features in the GeoJSON. Zooms to each individual polygon on click.

window.addEventListener("load", func1);
var map;

function func1() {
  map = new google.maps.Map(document.getElementById('map-canvas'), {
    zoom: 4,
    center: {
      lat: 0,
      lng: 0
    }
  });
  // Set the stroke width, and fill color for each polygon
  var featureStyle = {
    fillColor: '#ADFF2F',
    fillOpacity: 0.1,
    strokeColor: '#ADFF2F',
    strokeWeight: 1
  };

  // zoom to show all the features
  var bounds = new google.maps.LatLngBounds();
  map.data.addListener('addfeature', function(e) {
    processPoints(e.feature.getGeometry(), bounds.extend, bounds);
    map.fitBounds(bounds);
  });

  // zoom to the clicked feature
  map.data.addListener('click', function(e) {
    var bounds = new google.maps.LatLngBounds();
    processPoints(e.feature.getGeometry(), bounds.extend, bounds);
    map.fitBounds(bounds);
  });
  //Load mapdata via geoJson
  map.data.loadGeoJson('https://storage.googleapis.com/maps-devrel/google.json');
}

function processPoints(geometry, callback, thisArg) {
  if (geometry instanceof google.maps.LatLng) {
    callback.call(thisArg, geometry);
  } else if (geometry instanceof google.maps.Data.Point) {
    callback.call(thisArg, geometry.get());
  } else {
    geometry.getArray().forEach(function(g) {
      processPoints(g, callback, thisArg);
    });
  }
}
html,
body,
#map-canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map-canvas" style="border: 2px solid #3872ac;"></div>



回答2:


The Maps API (at least as of V3.26 today) supports Data.Geometry.prototype.forEachLatLng() which abstracts away the various Geometry types.

Given that you have already imported your geoJSON into map.data, it is easy to rezoom the map to fit ("fit-to-bounds"):

var bounds = new google.maps.LatLngBounds(); 
map.data.forEach(function(feature){
  feature.getGeometry().forEachLatLng(function(latlng){
     bounds.extend(latlng);
  });
});

map.fitBounds(bounds);

If your features are already being iterated for another reason (e.g. setting styles), you can work this code into your existing loop for efficiency.




回答3:


Hi please try the following code which worked perfectly fine, please replace the url with geojson file path..... thanks & reply back

$.ajax({
  url: url,
  dataType: 'JSON',
  success: function(data) {
    var lat = {}, lng = {};
    $(data.features).each(function(key,feature) {
      $(feature.geometry.coordinates[0]).each(function(key,val) {
        lng['max'] = (!lng['max'] || Math.abs(lng['max']) > Math.abs(val[0])) ? val[0] : lng['max'];
        lng['min'] = (!lng['min'] || Math.abs(lng['min']) < Math.abs(val[0])) ? val[0] : lng['min'];
        lat['max'] = (!lat['max'] || Math.abs(lat['max']) > Math.abs(val[1])) ? val[1] : lat['max'];
        lat['min'] = (!lat['min'] || Math.abs(lat['min']) < Math.abs(val[1])) ? val[1] : lat['min'];
      });
    });
    var bounds = new google.maps.LatLngBounds();
    bounds.extend(new google.maps.LatLng(lat.min - 0.01, lng.min - 0.01));
    bounds.extend(new google.maps.LatLng(lat.max - 0.01, lng.max - 0.01));
    map.fitBounds(bounds);
    map.setCenter(bounds.getCenter());
  }
});


来源:https://stackoverflow.com/questions/28507044/zoom-to-geojson-polygons-bounds-in-google-maps-api-v3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!