2014-11-05 72 views
1

當應用程序啓動時,我想將地圖視圖居中在用戶當前位置。我嘗試了兩種不同的方法,無法讓他們工作。第一個在小冊子中正常工作,但在開發過程中,我決定改用OL3。OL3:將地圖視圖中心設置爲geolocation.getCurrentPosition不起作用

第一種方法(在小葉工作):

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 
     }); 
} 

我的第二種方法是使用ol.Geolocation類:

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

的中心位置在創建視圖/地圖對象中:

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 
    }) 
}); 

我有一些疑慮,問題的原因是投影,但在其他r可以在變換圖層(WMTS,Vector),Geojson在不同座標系和ol.control.MousePosition中的源中正確使用投影。

我使用的是Firefox 32.0.3和geolocator插件開發/測試

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

+0

這可能有些變化是投影。你正在使用南部瑞典/挪威地區的UTM 32(以米爲單位),然後在4326中加載矢量數據,據推測,你想用前者來設置中心,對嗎?如果你可以在jsfiddle中提供一個簡單的工作例子,包括wms,它會有所幫助。 – 2014-11-06 08:33:51

+0

嗨,約翰。一個工作示例被添加到帖子。感謝您的關注。 – 2014-11-06 09:53:25

回答

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()); 
}); 

的代碼中最重要的部分是tracking: true:這意味着您需要定期檢查中心位置。

的第二個重要部分是對geolocation對象(的ol.Geolocation實例)

見的official examples地理位置樣本和API docs在綁定事件使根據您的要求