2017-06-21 191 views
0

我想在用戶找到自己後添加標記。Hopw使用mapboxgl.GeolocateControl添加標記到地圖框

我嘗試收聽地理定位事件,但沒有添加標記。 我應該如何繼續?

map.addControl(new mapboxgl.GeolocateControl({ 
    positionOptions: { 
     enableHighAccuracy: true, 
     watchPosition: true 
    } 
})); 
map.on('geolocate ',() => { 
    map.loadImage('images/pin2.png', (error, image, data) => { 
     if (error) throw error; 
     console.log(data); 
     map.addImage('pin2', image); 
     map.addLayer({ 
      "id": "points", 
      "type": "symbol", 
      "source": { 
       "type": "geojson", 
       "data": { 
        "type": "FeatureCollection", 
        "features": [{ 
         "type": "Feature", 
         "geometry": { 
          "type": "Point", 
          "coordinates": [data.position] 
         } 
        }] 
       } 
      }, 
      "layout": { 
       "icon-image": "pin2", 
       "icon-size": 1 
      } 
     }); 
    }); 
}); 
+0

是先計算出如果問題是地理定位的控制不射擊,或標記不可見,或兩者的某種組合。所以 - 如果您將代碼移動到「on('load' ...)''上,標記是否會顯示? –

回答

0

的地理定位的事件實際上是與地理定位的對象不是地圖對象

let geolocate = new mapboxgl.GeolocateControl({ 
    positionOptions: { 
     enableHighAccuracy: true, 
     watchPosition: true 
    } 
}); 

map.addControl(geolocate); 

geolocate.on('geolocate', (e) => { 
    map.loadImage('https://upload.wikimedia.org/wikipedia/commons/thumb/6/60/Cat_silhouette.svg/400px-Cat_silhouette.svg.png', (error, image) => { 
     console.log(e) 
     if (error) throw error; 
     map.addImage('cat', image); 
     map.addLayer({ 
      "id": "points", 
      "type": "symbol", 
      "source": { 
       "type": "geojson", 
       "data": { 
        "type": "FeatureCollection", 
        "features": [{ 
         "type": "Feature", 
         "geometry": { 
          "type": "Point", 
          "coordinates": [e.coords.longitude, e.coords.latitude] 
         } 
        }] 
       } 
      }, 
      "layout": { 
       "icon-image": "cat", 
       "icon-size": 0.3 
      } 
     }); 
    }); 
}); 

看看工作JSbin綁定在一起

+0

請注意,瀏覽器中的地理位置僅適用於https域。當連接不安全時,您將看不到地圖上的地理定位控件。 – Matijs