From 6f28fd0f9649ba5d2470779c307dba1337cd2d70 Mon Sep 17 00:00:00 2001
From: Anton Sarukhanov <code@ant.sr>
Date: Tue, 17 May 2016 22:16:59 -0400
Subject: [PATCH] Make Zoom To Vehicles go to the nearest vehicle when clicked.
 Fixes #8.

---
 bower.json         |  3 ++-
 static/js/map.js   | 15 +++++++--------
 templates/map.html |  1 +
 3 files changed, 10 insertions(+), 9 deletions(-)

diff --git a/bower.json b/bower.json
index 8aa20b7..2f304dd 100644
--- a/bower.json
+++ b/bower.json
@@ -18,6 +18,7 @@
     "jquery": "~2.2.3",
     "leaflet.markercluster": "~0.4.0",
     "leaflet-marker-rotate": "https://git.xhost.io/anton/leaflet-marker-rotate.git",
-    "Leaflet.label": "~0.2.1"
+    "Leaflet.label": "~0.2.1",
+    "Leaflet.GeometryUtil": "makinacorpus/Leaflet.GeometryUtil#^0.4.0"
   }
 }
diff --git a/static/js/map.js b/static/js/map.js
index 836785e..7694b32 100644
--- a/static/js/map.js
+++ b/static/js/map.js
@@ -486,15 +486,14 @@ BusMap.Map = function(opts) {
 
     // Go to zoom level and map center where vehicles are visible.
     function goToVehicles() {
+        if (Object.keys(that.vehicleMarkers).length == 0) return false;
         var zoom = BusMap.zoomShowVehicles;
-        var veh_keys = Object.keys(that.vehicleMarkers);
-        if (veh_keys.length > 0) {
-            var ll = that.vehicleMarkers[veh_keys[0]].getLatLng();
-        } else {
-            var ll = that.leaflet.getCenter();
-        }
-        console.log("setView("+ll+","+zoom+")");
-        that.leaflet.setView(ll, zoom);
+        var center = that.leaflet.getCenter();
+        // make vehicleMarkers an array because GeometryUtil can't handle obj/dict.
+        var vehicles = Object.keys(that.vehicleMarkers)
+                        .map(function(k) { return that.vehicleMarkers[k]; });
+        var goto_veh = L.GeometryUtil.closestLayer(that.leaflet, that.vehicleMarkers, center);
+        that.leaflet.setView(goto_veh.latlng, zoom);
     }
 
     init();
diff --git a/templates/map.html b/templates/map.html
index 438d678..5805de2 100644
--- a/templates/map.html
+++ b/templates/map.html
@@ -16,6 +16,7 @@
     <script src="bower/Leaflet.label/dist/leaflet.label.js"></script>
     <script src="bower/leaflet.markercluster/dist/leaflet.markercluster.js"></script>
     <script src="bower/leaflet-marker-rotate/leaflet.marker.rotate.js"></script>
+    <script src="bower/Leaflet.GeometryUtil/dist/leaflet.geometryutil.js"></script>
     <script src="bower/jquery/dist/jquery.min.js"></script>
     <script src="static/js/map.js"></script>
     <script>
-- 
GitLab