将标记放在OpenLayers中的Geolocation中 - 不起作用

时间:2016-02-24 09:05:16

标签: javascript geolocation openlayers-3

我尝试使用OpenLayers中的Geolocation类在我的位置放置IconFeature。地理位置功能工作了一段时间,但我还没能把标记放在我的位置。我已经关注了几十个例子,但仍然无法弄明白。所有图层都有效,但不是地理定位功能。我做错了什么?

    <!doctype html>
    <html lang="en">
      <head>
        <link rel="stylesheet" href="http://openlayers.org/en/v3.10.1/css/ol.css" type="text/css">

        <script src="http://openlayers.org/en/v3.10.1/build/ol.js" type="text/javascript"></script>
        <title>OpenLayers 3 example</title>
      </head>
      <body>
        <h2>My Map</h2>

        <div id="map" class="map">

   <script type="text/javascript">

            var olmap = new ol.Map({
                target: 'map',
                layers: layers,
                view: new ol.View({
                    center: [0, 0],
                    zoom: 1
            });

        var geolocation = new ol.Geolocation({
            tracking: true
        });

        geolocation.on('change', function (evt) {
            //save position and set map center
            var coords = geolocation.getPosition();
            olmap.getView().setCenter(coords);

            var iconFeature = new ol.Feature({
                geometry: new ol.geom.Point(pos)
            });
            var vectorSource = new ol.source.Vector({
                features: [iconFeature]
            });
            var vectorLayer = new ol.layer.Vector({
                source: vectorSource
            });


        var layers = [];
        layers[0] = new ol.layer.Tile({ source: new ol.source.MapQuest({ layer: 'sat' }) });
        layers[1] = new ol.layer.Tile({ source: new ol.source.OSM() });
        layers[2] = new ol.layer.Tile({
            source: new ol.source.TileWMS({
                url: 'http://localhost:8122/geoserver/topp/wms?',
                params: { LAYERS: 'states', VERSION: '1.1.0' }
            })
        });
        layers[3] = vectorLayer;

        </script>
   </div>
  </body>
</html>

1 个答案:

答案 0 :(得分:0)

您的代码有点令人困惑,但它可以像这样简单:

http://jsfiddle.net/jonataswalker/cLkuf5mt/

var iconFeature = new ol.Feature({
  geometry: new ol.geom.Point([])
});

var source = new ol.source.Vector({
  features: [iconFeature]
});
var vector = new ol.layer.Vector({
  source: source
});

var map = new ol.Map({
  target: document.getElementById('map'),
  view: new ol.View({
    center: [0, 0],
    zoom: 4,
    minZoom: 2,
    maxZoom: 20
  }),
  layers: [
    new ol.layer.Tile({
      source: new ol.source.MapQuest({layer: 'osm'})
    }),
    vector
  ]
});

var geolocation = new ol.Geolocation({
  tracking: true,
  projection: map.getView().getProjection()
});

geolocation.on('change', function(evt) {
  var coord = geolocation.getPosition();
  iconFeature.getGeometry().setCoordinates(coord);
  map.getView().setCenter(coord);
});