New Bee
New Bee

Reputation: 1047

Intersection point of two lines in leaflet

I want to get the intersection point of two polylines in leaflet. I have two lines as given below :-

var latlng1 = L.latLng(-7.9375, 4.46354);
var latlng2 = L.latLng(-7.96875, 16.11979);
var latlongs1 = [ latlng1, latlng2 ];
var polyline1 = L.polyline(latlongs1, {
    color : 'red'
}).addTo(map);


var latlng3 = L.latLng(-3.5625, 9.31719);
var latlng4 = L.latLng(-12.125, 9.50469);
var latlongs2 = [ latlng3, latlng4 ];
var polyline2 = L.polyline(latlongs2, {
    color : 'blue'
}).addTo(map);

I can get the bounds and latlongs of the endpoints of these lines. I can't get the contiguous array of all latlongs of line. Is there any way to get that ?

Upvotes: 3

Views: 3887

Answers (1)

Francisco Puga
Francisco Puga

Reputation: 25158

If you don't want to code all the logic, there is a small and easy to use library called Turf that provides several geoprocessing algorithms. You can even use just one of the algorithms mostly independent of the rest of the library.

The lineIntersects module does exactly what you want.

var intersection = turf.lineIntersect(polyline1.toGeoJSON(), polyline2.toGeoJSON());
var intersectionCoord = intersection.features[0].geometry.coordinates;

Also you can check the source code of the module for inspiration.

Upvotes: 3

Related Questions