将地图设置为angular6/openlayers中的变量 [英] Setting the map as a variable in angular6/openlayers
问题描述
我使用angular 6和openlayer 5.1.3.我成功完成了npm install ol --save
,然后我做到了
I use angular 6 and openlayers 5.1.3. I did npm install ol --save
successfully and then in my angular I did
import OlMap from 'ol/map';
import OlXYZ from 'ol/source/xyz';
import OlTileLayer from 'ol/layer/tile';
import OlView from 'ol/View';
import * as OlProj from 'ol/proj';
import 'ol/ol.css';
export class myComponent {
olmap: OlMap;
source: OlXYZ;
layer: OlTileLayer;
view: OlView;
//other, non-ol stuff
loading: boolean = false;
myname: String;
ngOnInit() {
this.source = new OlXYZ({
url:'http://tile.stamen.com/terrain/{z}/{x}/{y}.jpg'
});
this.layer = new OlTileLayer({
source: this.source
});
this.view = new OlView({
center: OlProj.fromLonLat([6.661594, 50.433237]),
zoom: 3,
});
const olmap = new OlMap({
target: 'map',
layers: [this.layer],
view: this.view
});
navigator.geolocation.getCurrentPosition(function(pos) {
const coords = OlProj.fromLonLat([pos.coords.longitude, pos.coords.latitude]);
olmap.getView().animate({center: coords, zoom: 10});
});
}//ngOnInit
这很好,但是问题是如果我这样做
This works fine, but the problem is that if I do
this.olmap = new OlMap({
target: 'map',
layers: [this.layer],
view: this.view
});
然后
navigator.geolocation.getCurrentPosition(function(pos) {
const coords = OlProj.fromLonLat([pos.coords.longitude, pos.coords.latitude]);
this.olmap.getView().animate({center: coords, zoom: 10});
});
我无法读取引用此this.olmap.getView().animate({center: coords, zoom: 10});
为什么我不能将olmap
与this.olmap
一起引用,因为我在Typescript中将其与其他变量一起定义了?我再也没有这个问题了,我总是访问this.x
Why I cannot refer to the olmap
with the this.olmap
, since I am defining it along with the other vars in Typescript? I never has this problem again, I always access values like this.x
为什么会出现此错误?这是什么意思?
Why do I get this error? What does it mean?
请解释一下,这样我就可以理解问题所在,并且可以毫无疑问地继续进行我的项目.
Please explain so I can understand what is wrong and can continue with my project, without having questions.
谢谢
推荐答案
您看到的问题与Javascript词法作用域有关.
The problem you are seeing relates to Javascript lexical scoping.
在Angular 6项目中,您可以使用ES6箭头函数访问父词法作用域,您的代码现在应该可以按预期运行:
In your Angular 6 project you can use an ES6 arrow function to access the parent lexical scope, your code should now behave as you are expecting:
navigator.geolocation.getCurrentPosition((pos) => {
const coords = OlProj.fromLonLat([pos.coords.longitude, pos.coords.latitude]);
this.olmap.getView().animate({center: coords, zoom: 10});
});
进一步阅读:
这篇关于将地图设置为angular6/openlayers中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!