14

Is there a way to get a shape to wrap from one edge across the dateline meridian (180° longitude) to appear on the other side of the map in Leaflet.js?

I've looked at:

But I'm unsure on what I could do to get it to reliably draw across the dateline...

0

4 Answers 4

24

Oh, you're hitting antimeridian artifacts. You're not the first one, and will not be the last one.

In Leaflet, there are basically two approaches for this problem:

1a: Cut the polygon beforehand

If you know your GIS tools, preprocess your polygon, so you end up with two (or possibly more) polygons. See «How can I make a polyline wrap around the world?».

Once you have a file with several polygons which don't cross the antimeridian, they should render fine. You will hit artifacts (namely, a vertical polygon border at the antimeridian, spanning the inside ofthe polygon) if you apply a border to the polygons, so you might want to cut a polygon and a polyline with the polygon's edge if you want to render both nicely.

1b: Cut the polygon on the browser

If you don't want to cut the polygon beforehand, you can let the web browser do it on the fly.

There are some utilities that can help here, but I'm going to point to Leaflet.VectorGrid in particular. By leveraging geojson-vt, it can cut polygons and their edges into tile-sized polygons and polygon edges. It can handle geometries crossing the antimeridian quite well.

You might want to look into geojson-vt directly, or maybe turf.js to do some on-the-fly geoprocessing.

2: Think outside the [-180..180] range

Leaflet can handle longitudes outside the [-180..180] range. In Leaflet, longitudes wrap only the TileLayer's tiles and not markers or polylines.

In other words: a marker at [0, -179] is shown at a different place than [0, 181]. See this answer for an example.

In other words: a line from [0, 179] to [0, -179] is 358 degrees long, but a line from [0, 179] to [0, 181] is two degrees long.

In other words: you can have linestrings or polygons with coordinates with longitudes outside the [-180..180] range, and that's fine for Leaflet. It's not fine for a lot of GIS software (in fact, I think that the new GeoJSON spec prohibits it). But it will make Leaflet happy.

2
  • Thank you! Is there a way that you could get a shape like a circle to wrap around a map? (Like without the worldCopyJump turned on)
    – Josef E.
    Commented Nov 14, 2016 at 14:53
  • No, not with the current algorithms. Commented Nov 14, 2016 at 18:18
5

When you are working with a cylindrical projection, as Leaflet does, it can be solved relatively easily with trigonometry. My solution is based on the first approach of Ivan's answer above, which is cutting the line in two parts at the 180th meridian. My solution is not perfect, as I will show below, but it is a good start.

Here is the code:

function addLineToMap(start, end) {
    if (Math.abs(start[1] - end[1]) > 180.0) {
        const start_dist_to_antimeridian = start[1] > 0 ? 180 - start[1] : 180 + start[1];
        const end_dist_to_antimeridian = end[1] > 0 ? 180 - end[1] : 180 + end[1];
        const lat_difference = Math.abs(start[0] - end[0]);
        const alpha_angle = Math.atan(lat_difference / (start_dist_to_antimeridian + end_dist_to_antimeridian)) * (180 / Math.PI) * (start[1] > 0 ? 1 : -1);
        const lat_diff_at_antimeridian = Math.tan(alpha_angle * Math.PI / 180) * start_dist_to_antimeridian;
        const intersection_lat = start[0] + lat_diff_at_antimeridian;
        const first_line_end = [intersection_lat, start[1] > 0 ? 180 : -180];
        const second_line_start = [intersection_lat, end[1] > 0 ? 180 : -180];

        L.polyline([start, first_line_end]).addTo(map);
        L.polyline([second_line_start, end]).addTo(map);
    } else {
        L.polyline([start, end]).addTo(map);
    }
}

This will calculate the latitude where the line crosses the 180th meridian, and draw the first line from the starting point to this latitude on the 180th meridian, and then a second one from this point to the end.

The picture below shows an example of the result.

Example

Even though I'm fairly certain the math checks out on my calculations, there is a small kink where the two lines are separated. I'm not sure whether this is due to the rendering of the Leaflet map, or an actual error in my calculations.

The starting point is [35.552299, 139.779999] and the end point is [64.81510162, -147.8560028].

The total longitudinal difference between the points is 72.364, and latitudinal difference is 29.263. Using the code below or an online calculator, the angle α is 22.018. Taking only the distance from the starting point to the 180th meridian, and the angle α, the latitudinal difference between starting point and intersection is 16.264. Adding the latitude of the starting point and this value, we get a latitude of 51.8166 at the 180th meridian. Drawing a straight line on a map tells me that this value should be slightly higher up, but I can't figure out why or how that is calculated.

If you want a curved line that accurately shows the curvate of the earth, I would highly recommend using Leaflet.Geodisic. It is easy to use and has a solution to the antimeridian problem built-in so you don't have to worry about it.

2
  • 5
    Nice simple approach! "there is a small kink where the two lines are separated": it is simply because your formula assumes Euclidean geometry, so it would render "fine" in equirectangular projection. But by default Leaflet uses Web Mercator projection, which stretches vertically higher latitudes.
    – ghybs
    Commented Dec 18, 2021 at 0:49
  • @ghybs Thank you, that makes a lot of sense. I have been wondering about that for a long time. Commented Dec 18, 2021 at 6:16
1

If you're using react-leaflet, the easiest way is to use it together with leaflet.geodesic and set the lines with leaflet.geodesic.

Import the required libraries

import { GeodesicLine } from "leaflet.geodesic"
import * as L from "leaflet"
import {
  MapContainer,
} from "react-leaflet"

Some points to join up across the meridian

 const East = new L.LatLng(-41.75412, 175.70595)
 const FurthurEast = new L.LatLng(-42.43624, -178.65339)
 const Chile = new L.LatLng(-26.74165, -71.41818)

In the return of your component:

<MapContainer
    center={centerMarker as [number, number]}
    zoom={5}
    whenCreated={(mapInstance) => {
         new GeodesicLine([East, FurthurEast, Chile], {
            weight: 10,
            color: "red",
          }).addTo(mapInstance)
    }}
>
{...children}
</MapContainer>
0

I came across this problem when I tracked a flight that crossed the antimeridian. -- The gpx format, in which my data is recorded, constrains all longitudes to be in the range [-180, 180[ and leaflet displays polylines (or polygons, for that matter) with lines crossing the antimeridian “folded around”. But, as pointed out by IvanSanchez, it can display points with coordinates outside the above range. So all you have to do is to “unfold” your original (longitude-constrained) coordinates. To this end, you go through the list of points in your polyline (or polygon) and check whether the line from point n to point n+1 crosses the antimeridian, and if so, in which direction (eastwards or westwards). This is actually quite easy (see below, the method relies on calculating the z-component of the cross product of the vectors corresponding to the two points, projected into the equatorial plane). If the line between point n and point n+1 crosses the antimeridian, then the longitudes of point n+1 and all subsequent points need to be increased or decreased by 360 degrees, depending on whether the antimeridian is crossed going eastwards or westwards -- until another crossing occurs. Then you let leaflet display your polyline or polygon based on the “unfolded” coordinates.

My code for this (in VB.NET) looks like this:

Private _Lat() As Double     ' this holds the latitude values of the points, but these remain unchanged in this context
Private _Lon() As Double

Public Sub Unfold()
    Dim d As Double = 0.0    ' this quantity is added to all longitudes and it is increased/decreased by 360.0 after each eastward/westward crossing of the antimeridian
    Dim l1 = _Lon(0)
    Dim l2 = _Lon(1)
    For i = 1 To _NoOfPoints - 1
        l2 = _Lon(i)
        Dim c = LineCrossesAntimeridian(l1, l2)
        If c > 0 Then d += 360.0
        If c < 0 Then d -= 360.0
        l1 = l2
        _Lon(i) += d
    Next
End Sub


Public Shared Function LineCrossesAntimeridian(ByVal Lon1 As Double, ByVal Lon2 As Double) As Integer
    ' Checks whether the (shortest) line from point P1 having longitude Lon1 to point P2 having longitude Lon2 crosses the antimeridian and returns
    '  0 if it does not
    '  1 if it does eastwards
    ' -1 if it does westwards

    If Lon1 = Lon2 OrElse Math.Sign(Lon1) = Math.Sign(Lon2) Then Return 0

    ' Dim v1 = New Vector(Math.PI / 2, Lon1.ToRad)
    ' Dim v2 = New Vector(Math.PI / 2, Lon2.ToRad)
    ' The sign of (v1 & v2).z indicates whether the movement from P1 to P2 is eastwards or westwards.
    ' If the sign of Lon1 is positive (i.e. P1 is in the eastern hemisphere) and we moved eastwards or
    ' if the sign of Lon1 is negative (i.e. P1 is in the western hemisphere) and we moved westwards,
    ' then we crossed the antimeridian (otherwise we crossed the prime meridian).
    ' The z-component of the cross product can be calculated, without creating the vectors, as follows:

    Dim z = Math.Cos(Lon1.ToRad) * Math.Sin(Lon2.ToRad) - Math.Cos(Lon2.ToRad) * Math.Sin(Lon1.ToRad)
    If Math.Sign(z) = Math.Sign(Lon1) Then
        Return Math.Sign(Lon1)
    Else
        Return 0
    End If
End Function

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.