我正在尝试添加基于html输入字段经度和纬度的位置标记。 在提供输入并单击search按钮(即调用函数goToLocation)后,结果应该在该位置上显示标记,但是在执行该函数后,只缩放了位置,而没有标记可见。 我使用的是open Layer4.5版本,下面是我的函数代码:
function goToLocation() {
vectorSource.clear();
var f = "{ \"type\": \"Feature\",\"geometry\": { \"type\": \"Point\", \"coordinates\": [" + $('#input-longitude').val() + "," + $('#input-latitude').val() + "]}}";
// var f2 = "{ \"type\": \"Feature\",\"geometry\": { \"type\": \"Point\", \"coordinates\": [" + $('#input-longitude').val() + "," + $('#input-latitude').val() + "]}}";
var iconStyle = new ol.style.Style({
image: new ol.style.Icon(/** @type {olx.style.IconOptions} */({
anchor: [0.5, 46],
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
opacity: 0.75,
src: 'img/marker.png'
}))
});
var myFeature = (new ol.format.GeoJSON()).readFeature(f);
myFeature.setStyle(iconStyle);
vectorSource.addFeature(myFeature);
map.getView().fit(vectorSource.getExtent(), map.getSize());
map.getView().fit(vectorSource.getExtent(), map.getSize());
map.getView().setZoom(12);
}
OL对输入类型是敏感的。 有时可以使用字符串作为坐标,有时则不行,它必须是一个浮点。
解决方案是解析坐标
parseFloat($('#input-longitude').val())
还要确保用户使用.
分隔小数,而不是,
PS:话虽如此,您不需要构造一个GeoJson并重新解析它。
myVectorSource.addFeature(
new Feature( {geometry: new Point([parseFloat($('#input-longitude').text()),
parseFloat($('#input-longitude').text())]),
name: String($('#input-myname').text()),
}));