How to get the extent of a GPX file to display it on a map (using openalyers)

女生的网名这么多〃 提交于 2020-01-03 05:54:10

问题


I am working on the GPX source example of openlayers 5.x available at https://openlayers.org/en/latest/examples/gpx.html

I am able to successfully load my GPX file and to display it on a map, but I have been unable to get its extent to know the min/max latitudes and longitudes to fit it dynamically on the map.

This is my code (identical to the example):

var GpxVector = new VectorLayer({
   source: new VectorSource({
      url: 'https://host.domain.com/filename.gpx',
      format: new GPX(),
   }),
   style: function(feature) {
      return GpxStyle[feature.getGeometry().getType()];
   }
});

map.addLayer(GpxVector);

The GPX file displays correctly but I am unable to get its extent to resize the map to zoom on it. I have tried:

console.log(GpxVector.getSource().getFeatures());

which gives no features to parse:

length: 0
__proto__: Array(0)

note that the source is there, and displays correctly on the map:

console.log(GpxVector.getSource());

gives:

c {disposed_: false, pendingRemovals_: {…}, dispatching_: {…}, listeners_: {…}, revision_: 0, …}

but there are no extent:

console.log(GpxVector.getSource().getExtent());

gives:

[Infinity, Infinity, -Infinity, -Infinity]

Also the VectorLayer has no extent:

console.log(GpxVector.getExtent());

gives:

undefined

Can someone help me and tell me how I can access the extents of the GPX file or at least its points so I can calculate it myself ?

Any help would be appreciated !


回答1:


The source won't load unless the layer is visible on the map. If you set an arbitrary opening center and zoom in the view, the source will load and then you can fit:

  // fit when the source loads
  GpxVector.getSource().on('addfeature', function(){
      map.getView().fit(GpxVector.getSource().getExtent());
  });

  // open the view to force a load
  map.getView().setCenter([0, 0]);
  map.getView().setZoom(0);


来源:https://stackoverflow.com/questions/56007763/how-to-get-the-extent-of-a-gpx-file-to-display-it-on-a-map-using-openalyers

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