Technologies:
Tolerim
a month ago
When using openLayer, an error is thrown stating that markerOverlay.setStyle is not a function.
I am trying to implement a map using the OpenLayers library that allows the user to select a location, and I can retrieve the corresponding latitude and longitude coordinates. Here is the code I have written:
var myMap = new ol.Map({
target: 'map',
key: 'web.a9393a343bdc4899afc43ae581f69d6d',
maptype: 'dreamy',
poi: true,
traffic: false,
view: new ol.View({
center: ol.proj.fromLonLat([51.338076, 35.699756]),
zoom: 14
})
});
var markerOverlay = new ol.Overlay({
element: document.createElement('div'),
positioning: 'center-center'
});
// set the style of the marker
var iconStyle = new ol.style.Style({
image: new ol.style.Icon({
src: '{{asset('images/marker.png')}}'
})
});
// add the marker overlay to the map
myMap.addOverlay(markerOverlay);
// listen for click events on the map
myMap.on('click', function(evt) {
// convert the clicked point's coordinates to lon-lat values
var lonLat = ol.proj.toLonLat(evt.coordinate);
// set the position of the marker overlay to the clicked point
markerOverlay.setPosition(evt.coordinate);
// set the style of the overlay to the default marker style
markerOverlay.setStyle(style);
console.log(lonLat)
});
However, when I load the page, no marker is displayed, and I receive the following error message after clicking on the map:
caught TypeError: markerOverlay.setStyle is not a function
I am unsure what the issue is.Answers(1)
Tolerim
a month ago
Verified Answer
The issue in the code is with the variable name used to define the iconStyle. In the code, the variable name used is "iconStyle", but in the line where it is set as the style of the markerOverlay, it is referred to as "style". This is causing the "markerOverlay.setStyle is not a function" error.
To fix this issue, change the following line:
markerOverlay.setStyle(style);
to:
markerOverlay.setStyle(iconStyle);
This should set the correct style for the markerOverlay and fix the error.