Openlayers 6 地理定位控制

Openlayers 6 geolocation control

我正在根据此 Openlayers workshop 重新设计地理位置控制功能,但我无法弄清楚我做错了什么。我收到错误消息:未捕获类型错误:无法读取 属性 'getExtent'。它应该指向正确的源文件。

  map.getView().fit(ol.interaction.extent.getExtent(), {
  maxZoom: 18,
  duration: 500
  });

完整代码在这里: https://jsfiddle.net/kaputkid/rnoL032z/19/

您错过了这部分教程:

const source = new ol.source.Vector();
const layer = new ol.layer.Vector({
  source: source
});
map.addLayer(layer);

你改变了这个:

  map.getView().fit(ol.interaction.extent.getExtent(), {
    maxZoom: 18,
    duration: 500
  });

根据教程应该是:

  if (!source.isEmpty()) {
    map.getView().fit(source.getExtent(), {
      maxZoom: 18,
      duration: 500
    });
  }

proof of concept fiddle

代码片段:

//add basemap
var BaseMap = new ol.layer.Tile({
  title: "Google Satellite",
  baseLayer: true,
  visible: true,
  source: new ol.source.TileImage({
    url: 'http://mt1.google.com/vt/lyrs=s&hl=pl&&x={x}&y={y}&z={z}'
  })
});

var map = new ol.Map({
  target: 'map',
  layers: [BaseMap],
  loadTilesWhileInteracting: true,
  view: new ol.View({
    center: ol.proj.transform([-76.5, 42.45], 'EPSG:4326', 'EPSG:3857'),
    zoom: 11
  }),
});
const source = new ol.source.Vector();
const layer = new ol.layer.Vector({
  source: source
});
map.addLayer(layer);


//add geoloaction
navigator.geolocation.watchPosition(function(pos) {
  const coords = [pos.coords.longitude, pos.coords.latitude];
  const accuracy = ol.geom.Polygon.circular(coords, pos.coords.accuracy);
  source.clear(true);
  source.addFeatures([
    new ol.Feature(accuracy.transform('EPSG:4326', map.getView().getProjection())),
    new ol.Feature(new ol.geom.Point(ol.proj.fromLonLat(coords)))
  ]);
}, function(error) {
  alert(`ERROR: ${error.message}`);
}, {
  enableHighAccuracy: true
});


const locate = document.createElement('div');
locate.className = 'ol-control ol-unselectable locate';
locate.innerHTML = '<button title="Locate me">◎</button>';
locate.addEventListener('click', function() {
  if (!source.isEmpty()) {
    map.getView().fit(source.getExtent(), {
      maxZoom: 18,
      duration: 500
    });
  }
});
map.addControl(new ol.control.Control({
  element: locate
}));
html,
body {
  width: 100%;
  height: 100%;
  padding: 0px;
  margin: 0px;
}

#map {
  width: 100%;
  height: 100%;
}

.locate {
  text-align: right;
  bottom: 0.5em;
  right: 0.5em;
}
<script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.5.0/build/ol.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.5.0/css/ol.css">
<div id="map" class="map"></div>