简体   繁体   中英

Displaying custom local image marker in OSM using OpenLayers

I have followed the tutorial on how to display a custom image as a marker from this article: https://medium.com/attentive-ai/working-with-openlayers-4-part-3-setting-customised-markers-and-images-on-map-da3369a81941

However, when using my own local project structure to reference my png image, it does not get rendered on the map.

Here is my current code:

var aPoint = new ol.geom.Point(ol.proj.fromLonLat([0, 0]))
var aFeature = new ol.Feature({
  geometry: aPoint
})
var aFeatureStyle = new ol.style.Style({
  image: new ol.style.Icon({
    //src: 'https://upload.wikimedia.org/wikipedia/commons/2/2a/Dot.png'
    src: '../../../dott.png'
  })
})
aFeature.setStyle(aFeatureStyle)
var aSource = new ol.source.Vector({
  features: [aFeature]
})
var aLayer = new ol.layer.Vector({
  source: aSource
})



var map = new ol.Map({
    target: 'map',
    layers: [
        new ol.layer.Tile({
            source: new ol.source.OSM(),
        }),
        aLayer
    ],
    view: new ol.View({
        center: ol.proj.fromLonLat([0, 0]),
        zoom: 14
    })
})

When using the src: ' https://upload.wikimedia.org/wikipedia/commons/2/2a/Dot.png ' variant, the required dot gets displayed, but when using src: '../../../dott.png' no markers are displayed.

I have definitely specified the right path to my local png file, so I am out of ideas why this code doesn't work.

I am using the Angular framework and running this on a local development server using Node.

So I finally figured it out, and I feel like I should've known this earlier, but since I'm new to Angular I didn't spot it straight away.

Any images that are needed to be referenced in source code in Angular need to be in src/assets/images folder in the Angular project structure. Then by specifying the path as src: '../assets/images/Dot.png' the image is successfully loaded with a 200 OK response, seen in the Network tab of a browser's Developer Tools.

That happened to me, I solved it by using

import imagePath from '../../../dott.png' 

and than using the imagePath variable instead using the path ../../../dott.png

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM