From ba466fe474572c67b3c5fbfe2b2699ee2bea2fb1 Mon Sep 17 00:00:00 2001 From: Markus Koch Date: Sun, 19 Apr 2020 22:00:35 +0200 Subject: [PATCH] leaflet-streets: Improve orientation detection for street names --- htdocs/leafletjs/Leaflet.streetlabels.js | 29 +++++++++++++----------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/htdocs/leafletjs/Leaflet.streetlabels.js b/htdocs/leafletjs/Leaflet.streetlabels.js index 8685ac9..1fb2754 100644 --- a/htdocs/leafletjs/Leaflet.streetlabels.js +++ b/htdocs/leafletjs/Leaflet.streetlabels.js @@ -126,8 +126,7 @@ L.StreetLabels = L.LabelTextCollision var stopCoords = layer.getLatLngs()[layer.getLatLngs().length - 1]; //Flip lineString if bearing is negative - if (this._getBearing(startCoords, stopCoords) < 0) - layer = this._getLineStringReverse(layer); + flip = (this._getBearing(startCoords, stopCoords) < 0); if (layer._parts) { ctx.textAlign = "center"; @@ -137,7 +136,7 @@ L.StreetLabels = L.LabelTextCollision //Build the points list for the first part var pathPoints = []; for (var i = 0; i < part.length; i++) { - var linePart = part[i]; + var linePart = (flip ? part[part.length - 1 - i] : part[i]); pathPoints.push(linePart.x); pathPoints.push(linePart.y); } @@ -158,16 +157,20 @@ L.StreetLabels = L.LabelTextCollision Source: https://makinacorpus.github.io/Leaflet.GeometryUtil/leaflet.geometryutil.js.html */ _getBearing: function (startCoords, stopCoords) { - var rad = Math.PI / 180, - lat1 = startCoords.lat * rad, - lat2 = stopCoords.lat * rad, - lon1 = startCoords.lng * rad, - lon2 = stopCoords.lng * rad, - y = Math.sin(lon2 - lon1) * Math.cos(lat2), - x = Math.cos(lat1) * Math.sin(lat2) - - Math.sin(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1); - var bearing = ((Math.atan2(y, x) * 180 / Math.PI) + 360) % 360; - return bearing >= 180 ? bearing - 360 : bearing; + if (startCoords.lat == stopCoords.lat) { + if (startCoords.lng > stopCoords.lng) + return -180; + else + return 180; + } + if (startCoords.lng == stopCoords.lng) { + if (startCoords.lat > stopCoords.lat) + return -90; + else + return 90; + } + var angle = Math.atan(stopCoords.lng - startCoords.lng, stopCoords.lat - startCoords.lat) * 180 / Math.Pi; + return angle; }, /**