我已经包含了源代码中的摘录以及下面的完整源代码。
我正在尝试将geoJSON添加到React中的mapbox-gl-js Map
类组件中,当运行如下所示的函数时,我收到错误cannot read property addSource of undefined
。我相信这是因为我使用了this.map
,但我不确定。我在哪里错了?
this.map.on('load', function() {
this.map.addSource("points", {
type: "geojson",
"data": nightlife_data,
})
this.map.addLayer({
"id": "points",
"type": "symbol",
"source": "points",
"layout": {
"icon-image": "{icon}-15",
"text-field": "{title}",
"text-font": ["Open Sans Semibold", "Arial Unicode MS Bold"],
"text-offset": [0, 0.6],
"text-anchor": "top"
}
})
mapboxgl.accessToken = accessToken;
class Map extends React.Component {
constructor(props){
super(props);
}
componentDidMount() {
getLocation(
(userLocation) => {
this.map = new mapboxgl.Map({
container: this.mapContainer,
zoom: 11.5,
center: userLocation,
style: "mapbox://styles/mapbox/light-v9"
})
this.map.addControl(
geocoder,
"top-left"
)
this.map.addControl(
locater,
"top-right"
)
const nightlife_data = request({
url: "https://api.foursquare.com/v2/venues/search",
method: 'GET',
qs: {
client_id: foursquareID,
client_secret: foursquareSecret,
ll: userLocation[0] + "," + userLocation[1],
categoryId: "4d4b7105d754a06376d81259",
v: '20170801',
limit: 1
}, function(err, res, body) {
if(err) {
console.error(err);
} else {
console.log(body);
}
}
})
this.map.on('load', function() {
this.map.addSource("points", {
type: "geojson",
"data": nightlife_data,
})
this.map.addLayer({
"id": "points",
"type": "symbol",
"source": "points",
"layout": {
"icon-image": "{icon}-15",
"text-field": "{title}",
"text-font": ["Open Sans Semibold", "Arial Unicode MS Bold"],
"text-offset": [0, 0.6],
"text-anchor": "top"
}
})
}
)
// automatically show the user location on map
setTimeout(locater._onClickGeolocate.bind(locater), 5)
})
}
componentWillUnmount() {
this.map.remove();
}
render() {
return <div className="map" ref={el => this.mapContainer = el} />;
}
}
export default Map;
答案 0 :(得分:1)
由于您使用的是function
,因此第二个this
与第一个map
不同,并且不包含您事先设置的this.map.on('load', function() {
this.map.addSource("points", {
type: "geojson",
"data": nightlife_data,
})
...
}
this
您可以尝试使用箭头功能,因为它会保留外部this.map.on('load', () => {
this.map.addSource("points", {
type: "geojson",
"data": nightlife_data,
})
...
}
(lexical scoping):
objfun