Skip to content

Instantly share code, notes, and snippets.

@ryancatalani
Last active April 17, 2024 18:28
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save ryancatalani/6091e50bf756088bf9bf5de2017b32e6 to your computer and use it in GitHub Desktop.
Save ryancatalani/6091e50bf756088bf9bf5de2017b32e6 to your computer and use it in GitHub Desktop.
Creating a curved line between two points on Leaflet. Read more: https://medium.com/@ryancatalani/creating-consistently-curved-lines-on-leaflet-b59bc03fa9dc
// Requires:
// Leaflet: http://leafletjs.com/
// Leaflet.curve: https://github.com/elfalem/Leaflet.curve
//
// Assumes:
// var map is a Leaflet map and already set up.
var latlngs = [];
var latlng1 = [LATITUDE, LONGTITUDE],
latlng2 = [LATITUDE, LONGTITUDE];
var offsetX = latlng2[1] - latlng1[1],
offsetY = latlng2[0] - latlng1[0];
var r = Math.sqrt( Math.pow(offsetX, 2) + Math.pow(offsetY, 2) ),
theta = Math.atan2(offsetY, offsetX);
var thetaOffset = (3.14/10);
var r2 = (r/2)/(Math.cos(thetaOffset)),
theta2 = theta + thetaOffset;
var midpointX = (r2 * Math.cos(theta2)) + latlng1[1],
midpointY = (r2 * Math.sin(theta2)) + latlng1[0];
var midpointLatLng = [midpointY, midpointX];
latlngs.push(latlng1, midpointLatLng, latlng2);
var pathOptions = {
color: 'rgba(255,255,255,0.5)',
weight: 2
}
if (typeof document.getElementById('LEAFLET_MAP').animate === "function") {
var durationBase = 2000;
var duration = Math.sqrt(Math.log(r)) * durationBase;
// Scales the animation duration so that it's related to the line length
// (but such that the longest and shortest lines' durations are not too different).
// You may want to use a different scaling factor.
pathOptions.animate = {
duration: duration,
iterations: Infinity,
easing: 'ease-in-out',
direction: 'alternate'
}
}
var curvedPath = L.curve(
[
'M', latlng1,
'Q', midpointLatLng,
latlng2
], pathOptions).addTo(map);
@spmsupun
Copy link

Thanks, we were searching this forever

@ckotyan
Copy link

ckotyan commented Jun 24, 2019

Thank you Ryan for this. It saved tonne of time for me. Appreciate your article.

@lawanya14
Copy link

when i have connect location through curve but i get error L.curve is not constructor please suggest me

@jgourinda
Copy link

👍 Even more for the great graphics in the medium article

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment