I am trying to point my address on a map in OpenLayers by using the code below :
var rome = new ol.Feature({
geometry: new ol.geom.Point(ol.proj.fromLonLat([12.5, 41.9]))
});
rome.setStyle(new ol.style.Style({
image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
color: '#8959A8',
crossOrigin: 'anonymous',
src: 'https://openlayers.org/en/v4.3.1/examples/data/dot.png'
}))
}));
var vectorSource = new ol.source.Vector({
features: [rome]
});
var vectorLayer = new ol.layer.Vector({
source: vectorSource
});
var rasterLayer = new ol.layer.Tile({
source: new ol.source.TileJSON({
url: 'https://api.tiles.mapbox.com/v3/mapbox.geography-class.json?secure',
crossOrigin: ''
})
});
var map = new ol.Map({
layers: [rasterLayer, vectorLayer],
target: document.getElementById('map'),
view: new ol.View({
center: ol.proj.fromLonLat([2.896372, 44.60240]),
zoom: 3
})
});
I have one input field onchange
of that input field I will get the values of latitude and longitude.
I want to place those values on my point, so I have stored values I'm getting in global variable and accessing in my JS: [longitude, latitude]
)
but it is not placing those values on map. but if i place values like 4.1111, 50.1111
, it works.
When I change my input values [longitude, latitude]
changes but not apply on the below code :
var rome = new ol.Feature({
geometry: new ol.geom.Point(ol.proj.fromLonLat([longitude, latitude]))
});
So your function with creating new feature is executing without filled variables? The code was executed and change in variables will not refresh the feature properties. You need to run function in onchange event. If you are not using any JS framework (Angular, React, Vue etc.) take a look for a plain JS solution ith button on jsfiddle.
HTML:
<input id="x" type="number" step="0.0001" value="4.1111">
<input id="y" type="number" step="0.0001" value="50.1111">
<button id="button">Add point</button>
<div id="map"></div>
JS:
var map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
target: 'map',
view: new ol.View({
center: [0, 0],
zoom: 2
})
})
document.getElementById("button").addEventListener("click", function( event ) {
var x = parseFloat(document.getElementById('x').value)
var y = parseFloat(document.getElementById('y').value)
var feature = new ol.Feature({
geometry: new ol.geom.Point(ol.proj.transform([x, y], 'EPSG:4326',
'EPSG:3857'))
})
var vectorSource = new ol.source.Vector({
features: [feature]
})
var vectorLayer = new ol.layer.Vector({
source: vectorSource,
})
map.addLayer(vectorLayer)
}, false)