Mapbox GL 地图不以初始位置为中心

Ame*_*she 1 google-maps mapbox mapbox-gl mapbox-gl-js angular

我在 Angular 2 中使用 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);
Run Code Online (Sandbox Code Playgroud)

}

在此示例中,我使用坐标 41.8692324 -87.6630301,即芝加哥(根据我的控制台日志,我可以验证初始化地图时坐标是否存在)。我从谷歌地方获取这些坐标。当我运行地图时,由于某种原因它以南极洲为中心:

在此输入图像描述

我为此使用默认样式和图块集。我应该怎么办?

Red*_*dor 6

您的纬度/经度方向错误!

另外,建议您考虑用户是否拒绝访问地理位置信息 (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
});
}
Run Code Online (Sandbox Code Playgroud)
body { margin:0; padding:0; }
#map { position:absolute; top:0; bottom:0; width:100%; }
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)