ho3ein
ho3ein

Reputation: 11

how to set leaflet marker to center of div tag in leafletjs

I want the marker to be in the center of the map, but it is wrong. I read the rest of the articles, but my problem was not solved.

	var map = L.map('map').setView([lat, lng], 18);

L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk', {
    maxZoom: 18,
    id: 'mapbox.streets',
    accessToken: 'pk',
    attribution: 'nemajoo',
    watch: true
}).addTo(map);
var LeafIcon = L.Icon.extend({
    options: {

        iconSize:     [28, 60],
        shadowSize:   [50, 64],
        iconAnchor:   [22, 94],
        shadowAnchor: [4, 62],
        popupAnchor:  [-3, -76]
    }
});
var greenIcon = new LeafIcon({iconUrl: 'images/mrk.png'});
var center = map.getCenter();
var marker = L.marker([center.lat, center.lng],{icon: greenIcon}).addTo(map);

Upvotes: 0

Views: 847

Answers (1)

Jalu
Jalu

Reputation: 329

The problem here could be in any of the 3 configurations given we don't have the image:

  • mrk.png has some spacing inside the image, this can be fixed with any image editing tool.
  • the options object, on the anchor tag moves the image, making it look like it's not centered.
  • When you set the center, as far as I can see, you first get the center from the map, then use this center to position the icon, this is nicely done but markers with distant zooming don't represent it's center accurately.

In resume: The problem is on the png or the anchor configuration, modify those values and try again.

If this does not work you can upload a sample minimal project so we can check (don't upload api keys or similar)

Upvotes: 1

Related Questions