Mapbox GL - my basic, default marker won´t show up

2019-07-26 19:54发布

问题:

lately, I started fiddling with MapBox and right now, I am trying to add the marker to the map. Not as easy as it seems. I am trying to add basic, default marker with code copypasted straight out of "Mapbox GL" reference guide. Still, it won´t show up.

This is the code I use, it cant get simpler that this...

var marker = new mapboxgl.Marker().setLngLat([45.702117, 42.395926]).addTo(map);

Does anybody have an idea why it doesnt work? Whole "not working scenario" can be seen at http://www.caucasus-trekking.com/Maps/map

Edit: Specifically, I would like to use that classic marker, round at the top and pointy at the bottom. Somjething like this - https://www.mapbox.com/help/img/android/marker-example.png

Wasnt there some default shape in Mapbox or should I create it by my own css file?

Thanks a lot

回答1:

Somewhat strangely, it appears that the answer is that the Marker is being drawn, but there is no styling included in mapbox-gl.css to actually make it visible. It's just an invisible div.

So you need to add some CSS:

.mapboxgl-marker {
    width: 25px;
    height: 25px;
    border-radius: 50%;
    border:1px solid gray;
    background-color:lightblue;
}

See codepen: https://codepen.io/stevebennett/pen/VpPbbM



回答2:

If you look into the source of your page, you'll see that the marker is successfully added as an empty <div class="mapbox-gl-marker" ...></div>. Yes, nothing to see here, but that's the default way it is.

Show that marker some love and give it some style.

var el = document.createElement('div');                                       
el.style.backgroundImage = 'url(https://placekitten.com/g/50/)';              
el.style.width = '50px';                                                      
el.style.height = '50px';
el.style.borderRadius = '50%';                                                     
new mapboxgl.Marker(el).setLngLat([45.702117, 42.395926]).addTo(map);

See the original source of this c&p code in this example.