我想根据html输入的经度和纬度,在特定位置上添加标记。在提供输入后,点击搜索按钮,即调用函数goToLocation,结果应该在该位置上显示标记,但在执行该函数后,只有位置被放大,而看不到标记。我使用的是open layer 4.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()),
}));