2017-09-20 65 views
0

我在Angular 2中使用mapbox gl来根据用户的当前位置绘制地图。我的代码去如下:Mapbox GL地图没有集中在初始位置

executemap() { 
console.log(this.locationService.currentLat, this.locationService.currentLng); 
this.map = new mapbox.Map({ 
    style: 'mapbox://styles/mapbox/streets-v10', 
    center: [this.locationService.currentLat, this.locationService.currentLng], 
    zoom: 9, 


    container: 'map' 
}); 


console.log('map loaded'); 
console.log(this.map); 
    console.log(this.map.getCenter().toString()); 
var latLng = new mapbox.LngLat(this.locationService.currentLat,this.locationService.currentLng); 
this.map.resize(); 
this.map.setZoom(2); 

}

在这个例子中

,我使用的坐标41.8692324 -87.6630301,这是芝加哥(根据我的控制台日志,我可以确认的是,坐标是那里当初始化地图)。我从谷歌的地方得到这些坐标。当我跑地图,由于某种原因,集中在南极洲:

enter image description here

我使用的是默认的样式和地形设置此。我该怎么办?

回答

1

您的Lat/Lng方向错误!

此外,它建议您考虑用户是否拒绝访问地理位置信息(IP)。我会建议添加一个默认的纬度/经度,以回落,也许是一个消息 - 在这个例子中默认为纽约。

var options = { 
 
    enableHighAccuracy: true, 
 
    timeout: 5000, 
 
    maximumAge: 0 
 
}; 
 

 
function success(pos) { 
 
    crd = pos.coords; 
 
    loadMap(crd.longitude,crd.latitude); 
 
}; 
 

 
function error(err) { 
 
    console.log(`ERROR(${err.code}): ${err.message}`); 
 
    loadMap(-73.935242,40.730610); 
 
}; 
 

 
navigator.geolocation.getCurrentPosition(success, error, options); 
 

 
function loadMap(lng,lat) { 
 
mapboxgl.accessToken = 'pk.eyJ1IjoiZGF2aWRiYXR0eSIsImEiOiJjajBqc2hqZ3YwMDN5MndvbDUxaDhoMDV6In0.w7sfrB5JeCH92sY-l0TQSg'; 
 
var map = new mapboxgl.Map({ 
 
    container: 'map', // container id 
 
    style: 'mapbox://styles/mapbox/streets-v9', // stylesheet location 
 
    center: [lng,lat], // starting position [lng, lat] 
 
    zoom: 9 // starting zoom 
 
}); 
 
}
body { margin:0; padding:0; } 
 
#map { position:absolute; top:0; bottom:0; width:100%; }
<link href="https://api.tiles.mapbox.com/mapbox-gl-js/v0.40.1/mapbox-gl.css" rel="stylesheet"/> 
 
<script src="https://api.tiles.mapbox.com/mapbox-gl-js/v0.40.1/mapbox-gl.js"></script> 
 

 
<div id='map'></div>