当应用程序启动时,我希望将地图视图集中在用户的当前位置。我尝试了两种不同的方法,但都无法成功。第一个在传单中工作正常,但在开发过程中,我决定使用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
});
}
我的第二种方法是使用ol。地理位置类别:
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
})
});
我有一些怀疑,问题的原因是投影,但另一方面,投影在转换层(WMTS,Vector)中工作正常,源于不同坐标系统中的Geojson和ol.control.MousePosition.
我正在使用Firefox 32.0.3和地理定位器插件来开发/测试
中的工作示例http://jsfiddle.net/AndersFinn/ak4zotn8/
在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
的实例)上绑定事件
请参阅官方示例中的地理位置示例和API文档,根据您的需求进行一些更改