2016-10-15 1 views
0

マップ上にマーカーを置くことはできませんが、その位置は動的に更新されます。 ジオロケーションの関数内でレイヤーを作成すると( 'change'イベントは機能しますが、ジオロケーションが変更されるたびにレイヤーが追加されるため、その関数の外にレイヤーを作成し、マーカーfolowingコードでOpenlayersでのジオロケーションマーカーの位置の更新3

私は 'TypeError例外を:aがnullである' 取得。

var geolocation = new ol.Geolocation({ 
    projection: map.getView().getProjection(), 
    tracking: true, 
    trackingOptions: { 
    enableHighAccuracy: true, 
    maximumAge: 2000 
    } 
});  

var iconStyle = new ol.style.Style({ 
    image: new ol.style.Icon({ 
    anchor: [0.5, 46], 
    anchorXUnits: 'fraction', 
    anchorYUnits: 'pixels', 
    opacity: 0.75, 
    src: './_img/marker_.png' 
    }) 
}); 

var pos1 = geolocation.getPosition(); 

var iconFeature = new ol.Feature({ 
    geometry: new ol.geom.Point(pos1) 
});   
var iconSource = new ol.source.Vector({ 
    features: [iconFeature] 
}); 
var iconLayer = new ol.layer.Vector({ 
    source: iconSource, 
    style : iconStyle 
}); 

map.addLayer(iconLayer); 

geolocation.on('change', function() { 
    var pos_upd = geolocation.getPosition(); 
    iconFeature.getGeometry().setCoordinates(pos_upd); 
    view.setCenter(pos_upd); 
    view.setZoom(18);   
}); 

答えて

0

コードを少し変更しました。最初に、ol.geom.Point() - positionにバインドされていなかったiconFeatureを最初に作成しました。このようにして、geolocation.getPosition()を使用する必要はありませんでした。 後でgeolocation.on( 'change') - イベント私は実際の位置をiconFeatureのジオメトリに割り当てました。

espected

// add an empty iconFeature to the source of the layer 
    var iconFeature = new ol.Feature(); 
    var iconSource = new ol.source.Vector({ 
    features: [iconFeature] 
    });  
    var iconLayer = new ol.layer.Vector({ 
    source: iconSource, 
    style : iconStyle 
    });  
    map.addLayer(iconLayer); 

// Update the position of the marker dynamically and zoom to position 
    geolocation.on('change', function() { 
    var pos = geolocation.getPosition(); 
    iconFeature.setGeometry(new ol.geom.Point(pos)); 
    view.setCenter(pos); 
    view.setZoom(18); 
    }); 
のように動作します
0

ol.GeolocationによってラップされたブラウザジオロケーションAPIは、非同期で開始した後、geolocation.getPosition()は常にundefinedを返します。最初の変更イベントまで。

適切なことは、座標を取得した後で、変更イベントハンドラにフィーチャを追加することです。

ore関数を追加するかどうかを判断するには、条件を使用する必要があります。

関連する問題