OL3:将地图视图中心设置为geolocation.getCurrentPosition不起作用

And*_*sen 1 proj4js leaflet openlayers-3

当应用程序启动时,我想将地图视图置于用户当前位置的中心位置.我尝试了两种不同的方法,无法让它们发挥作用.第一个在传单中正常工作,但在开发过程中我决定使用OL3.

第一种方法(在传单中工作):

  var myProjectionName = "EPSG:25832";
  proj4.defs(myProjectionName,
             "+proj=utm +zone=32 +ellps=GRS80 +units=m +no_defs");

 var centerPosition;

 if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(
        function (pos) {
                 centerPosition =             
                            ol.proj.transform(
                                     [position.coords.longitude,
                                      position.coords.latitude],
                                     'EPSG:4326', 
                                      myProjectionName);
        },
        function (err) {centerPosition = [724844,6178000];},
        {
            enableHighAccuracy: false,
            timeout: 5000,
            maximumAge: 1000  
        });
}
Run Code Online (Sandbox Code Playgroud)

我的第二种方法是使用ol.Geolocation类:

 var proj1 = ol.proj.get(myProjectionName);
 var geolocation = new ol.Geolocation({
                             projection: proj1
                       });
 var centerPosition= geolocation.getPosition();
Run Code Online (Sandbox Code Playgroud)

中心位置用于创建视图/贴图对象:

var map = new ol.Map({
   target: 'map',
   logo : false,
   layers: [ GSTGroup, OVLGroup, SheatLayer],
   view: new ol.View({
      projection: myProjectionName,
      center: centerPosition,
      resolutions : AVLresolutions,
      resolution : 2
     })
});
Run Code Online (Sandbox Code Playgroud)

我有一些疑问,问题的原因是投影,但另一方面,投影在转换图层(WMTS,Vector),Geojson在不同坐标系和ol.control.MousePosition中的来源中正常工作.

我正在使用Firefox 32.0.3和geolocator插件进行开发/测试

http://jsfiddle.net/AndersFinn/ak4zotn8/中的工作示例

Tho*_*ier 5

map声明后添加以下内容(已测试):

var proj1 = ol.proj.get(myProjectionName);
var geolocation = new ol.Geolocation({
    projection: myProjectionName,
    tracking: true
});

geolocation.on('change', function(evt) {
  console.log(geolocation.getPosition());
  map.getView().setCenter(geolocation.getPosition());
});
Run Code Online (Sandbox Code Playgroud)

最重要的部分在于tracking: true代码:它意味着您定期检查位置到中心.

第二个重要的部分是绑定geolocation对象上的事件(一个实例ol.Geolocation)

请参阅官方示例中的地理位置示例和API文档,以根据您的要求进行一些更改