How to project pixel coordinates in leaflet?

DeEgge picture DeEgge · Oct 29, 2013 · Viewed 8.8k times · Source

I am trying to create a map based on an image which is 16384x16384 px, but I would also like to add markers at specific locations using pixel coordinates of this given image.

I created a tile layer, a map element and set maximum boundaries, so that I can't scroll out of the image, using this code:

    var map = L.map('map', {
        maxZoom: 6,
        minZoom: 2,
        crs: L.CRS.Simple
    }).setView([0, 0], 2);
    var southWest = map.unproject([0,16384], map.getMaxZoom());
    var northEast = map.unproject([16384,0], map.getMaxZoom());
    map.setMaxBounds(new L.LatLngBounds(southWest, northEast));

    L.tileLayer('tiles/{z}/{x}/{y}.png', {
        tms: true
    }).addTo(map);

The points i'd like to add to the map are stored in an external file as GeoJSON, and they look like this http://www.de-egge.de/maps/terranigma/terraPoints.js

I load them using this snippet of code:

var terraPoints = new L.geoJson(points, {
        onEachFeature: function (feature, layer) {
            layer.bindPopup(
                "<b>Ort: </b>" + feature.properties["points[, 1]"] 
            );
        }
    });

    map.addLayer(terraPoints);

But of course, they don't show up, because the reference systems don't match. The points use pixel coordinates, but my map uses geographic coordinates.

Is there a way to "unproject" the points while loading them?

Any help is much appreciated and thanks in advance!

Answer

user3011220 picture user3011220 · Nov 21, 2013
    var geoJsonTest = new L.geoJson(geojsonFeature, {
    coordsToLatLng: function (newcoords) {
        return (map.unproject([newcoords[1], newcoords[0]], map.getMaxZoom()));
    },
    pointToLayer: function (feature, coords) {      
        return L.circleMarker(coords, geojsonMarkerOptions);
    }
});

This is how you use in case you didn't figure it out yet. Seeing the coordinates are inverted I changed them around in the option. Works for perfectly for me.