How do switch Leaflet coordinates to where 0,0 is

2019-08-15 10:02发布

问题:

I am working on a leaflet project where I need the coordinates 0 to 4096 and which the leaflet coordinates that I need are the following:

0,0 bottom left (southWest)
0,4096' top left (northWest)
4096',4096' top right (northEast)
4096',0 bottom right (southEast)

I have tried many things to get the coordinates to map as needed but no luck. Here is my jsfiddle with my example, which has a console.log when you click on the map which shows the coordinates. If you click in the top left you will see its 0,0 and if you click in the bottom right you will see 4096,4096 which is backwards from whats needed. Here is my code that I have

url = 'http://{s}.tile.osm.org/{z}/{x}/{y}.png';
weight = 4096;
height = 4096;
mapMinZoom = 1;
mapMaxZoom = 7;
map = L.map('map', {
  maxZoom: mapMaxZoom,
  minZoom: mapMinZoom,
  noWrap: true,
  detectRetina: true
});
unproject = function(coord) {
  return map.unproject(coord, 4);
};

southWest = unproject([0, 0]);
northEast = unproject([height, weight]);
map.setMaxBounds(new L.LatLngBounds(southWest, northEast));
tileLayer = L.tileLayer(url, {
  minZoom: mapMinZoom,
  maxZoom: mapMaxZoom,
  noWrap: true,
  tileSize: 256,
  detectRetina: false
}).addTo(map);

map.setView(unproject([0, 0]), 2);

map.on('click', function(e) {
  var coords, latLong;
  latLong = new L.LatLng(e.latlng.lat, e.latlng.lng);
  coords = map.project(latLong, 4);
  console.log("x="+coords.x+", y="+coords.y);
});

回答1:

If I understand correctly, you would like a map coordinates like this:

[0, 4096] .. [4096, 4096]
.........................
.........................
[0, 0] ........ [4096, 0]

It is good as vertical coordinate increases while going up (like latitude on Leaflet) and horizontal coordinate increases while going right (like longitude on Leaflet). So you do not seem to need to invert the vertical axis.

As for the order of the coordinates, unfortunately Leaflet uses latitude first, longitude second, and it is almost impossible to switch them natively. However, you can easily build a wrapper method that just swaps the coordinates. (similar to Leaflet LatLngBounds with simpler CRS & projection, but no need to use negative vertical coordinate -y since in your case you want it in the same direction as latitude)

Then another question would be how you want the coordinates in-between those 4 corners. The default CRS (Web Mercator) is not linear along the vertical axis. If you need your coordinates to be linear, you should use L.CRS.Simple. See Leaflet tutorial for non-Earth-based maps.