Skip to content

Instantly share code, notes, and snippets.

@mfd
Last active September 3, 2018 06:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mfd/a49a83260ecf1c6b6682fec668b6128d to your computer and use it in GitHub Desktop.
Save mfd/a49a83260ecf1c6b6682fec668b6128d to your computer and use it in GitHub Desktop.
Custom maps for Strava
//javascript:jQuery('body').append(jQuery("<script src='http://localhost:1984/_inject.js'></script>"));void(0);
// jQuery('body').append(jQuery("<script src='http://localhost:1984/_inject.js'></script>"));void(0);
/*
* Map switcher for Strava website.
*
* Copyright © 2016 Tomáš Janoušek.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
(function(){
var baseUrl = null;
if (document.currentScript) {
var m = document.currentScript.src.match("http.*/");
if (m) {
baseUrl = m;
}
}
function getURL(path) {
if (baseUrl) {
return baseUrl + path;
} else {
return chrome.extension.getURL(path);
}
}
function inject() {
document.arrive(".leaflet-container", {onceOnly: false, existing: true}, function(){
var s = document.createElement("script");
s.src = getURL('fix.js');
s.type = 'text/javascript';
s.dataset.googleJsUrl = getURL('Google.js');
s.dataset.layersUrl = getURL('layers.js');
document.body.appendChild(s);
});
}
if (document.currentScript) {
jQuery.getScript(getURL('arrive.min.js')).done(function(){
inject();
});
} else {
inject();
}
})();
/*
* arrive.js
* v2.3.1
* https://github.com/uzairfarooq/arrive
* MIT licensed
*
* Copyright (c) 2014-2016 Uzair Farooq
*/
var Arrive=function(a,b,c){"use strict";function l(a,b,c){e.addMethod(b,c,a.unbindEvent),e.addMethod(b,c,a.unbindEventWithSelectorOrCallback),e.addMethod(b,c,a.unbindEventWithSelectorAndCallback)}function m(a){a.arrive=j.bindEvent,l(j,a,"unbindArrive"),a.leave=k.bindEvent,l(k,a,"unbindLeave")}if(a.MutationObserver&&"undefined"!=typeof HTMLElement){var d=0,e=function(){var b=HTMLElement.prototype.matches||HTMLElement.prototype.webkitMatchesSelector||HTMLElement.prototype.mozMatchesSelector||HTMLElement.prototype.msMatchesSelector;return{matchesSelector:function(a,c){return a instanceof HTMLElement&&b.call(a,c)},addMethod:function(a,b,c){var d=a[b];a[b]=function(){return c.length==arguments.length?c.apply(this,arguments):"function"==typeof d?d.apply(this,arguments):void 0}},callCallbacks:function(a){for(var c,b=0;c=a[b];b++)c.callback.call(c.elem)},checkChildNodesRecursively:function(a,b,c,d){for(var g,f=0;g=a[f];f++)c(g,b,d)&&d.push({callback:b.callback,elem:g}),g.childNodes.length>0&&e.checkChildNodesRecursively(g.childNodes,b,c,d)},mergeArrays:function(a,b){var d,c={};for(d in a)c[d]=a[d];for(d in b)c[d]=b[d];return c},toElementsArray:function(b){return"undefined"==typeof b||"number"==typeof b.length&&b!==a||(b=[b]),b}}}(),f=function(){var a=function(){this._eventsBucket=[],this._beforeAdding=null,this._beforeRemoving=null};return a.prototype.addEvent=function(a,b,c,d){var e={target:a,selector:b,options:c,callback:d,firedElems:[]};return this._beforeAdding&&this._beforeAdding(e),this._eventsBucket.push(e),e},a.prototype.removeEvent=function(a){for(var c,b=this._eventsBucket.length-1;c=this._eventsBucket[b];b--)a(c)&&(this._beforeRemoving&&this._beforeRemoving(c),this._eventsBucket.splice(b,1))},a.prototype.beforeAdding=function(a){this._beforeAdding=a},a.prototype.beforeRemoving=function(a){this._beforeRemoving=a},a}(),g=function(b,d){var g=new f,h=this,i={fireOnAttributesModification:!1};return g.beforeAdding(function(c){var i,e=c.target;c.selector,c.callback;(e===a.document||e===a)&&(e=document.getElementsByTagName("html")[0]),i=new MutationObserver(function(a){d.call(this,a,c)});var j=b(c.options);i.observe(e,j),c.observer=i,c.me=h}),g.beforeRemoving(function(a){a.observer.disconnect()}),this.bindEvent=function(a,b,c){b=e.mergeArrays(i,b);for(var d=e.toElementsArray(this),f=0;f<d.length;f++)g.addEvent(d[f],a,b,c)},this.unbindEvent=function(){var a=e.toElementsArray(this);g.removeEvent(function(b){for(var d=0;d<a.length;d++)if(this===c||b.target===a[d])return!0;return!1})},this.unbindEventWithSelectorOrCallback=function(a){var f,b=e.toElementsArray(this),d=a;f="function"==typeof a?function(a){for(var e=0;e<b.length;e++)if((this===c||a.target===b[e])&&a.callback===d)return!0;return!1}:function(d){for(var e=0;e<b.length;e++)if((this===c||d.target===b[e])&&d.selector===a)return!0;return!1},g.removeEvent(f)},this.unbindEventWithSelectorAndCallback=function(a,b){var d=e.toElementsArray(this);g.removeEvent(function(e){for(var f=0;f<d.length;f++)if((this===c||e.target===d[f])&&e.selector===a&&e.callback===b)return!0;return!1})},this},h=function(){function h(a){var b={attributes:!1,childList:!0,subtree:!0};return a.fireOnAttributesModification&&(b.attributes=!0),b}function i(a,b){a.forEach(function(a){var c=a.addedNodes,d=a.target,f=[];null!==c&&c.length>0?e.checkChildNodesRecursively(c,b,k,f):"attributes"===a.type&&k(d,b,f)&&f.push({callback:b.callback,elem:node}),e.callCallbacks(f)})}function k(a,b,f){if(e.matchesSelector(a,b.selector)&&(a._id===c&&(a._id=d++),-1==b.firedElems.indexOf(a._id))){if(b.options.onceOnly){if(0!==b.firedElems.length)return;b.me.unbindEventWithSelectorAndCallback.call(b.target,b.selector,b.callback)}b.firedElems.push(a._id),f.push({callback:b.callback,elem:a})}}var f={fireOnAttributesModification:!1,onceOnly:!1,existing:!1};j=new g(h,i);var l=j.bindEvent;return j.bindEvent=function(a,b,c){"undefined"==typeof c?(c=b,b=f):b=e.mergeArrays(f,b);var d=e.toElementsArray(this);if(b.existing){for(var g=[],h=0;h<d.length;h++)for(var i=d[h].querySelectorAll(a),j=0;j<i.length;j++)g.push({callback:c,elem:i[j]});if(b.onceOnly&&g.length)return c.call(g[0].elem);setTimeout(e.callCallbacks,1,g)}l.call(this,a,b,c)},j},i=function(){function d(a){var b={childList:!0,subtree:!0};return b}function f(a,b){a.forEach(function(a){var c=a.removedNodes,f=(a.target,[]);null!==c&&c.length>0&&e.checkChildNodesRecursively(c,b,h,f),e.callCallbacks(f)})}function h(a,b){return e.matchesSelector(a,b.selector)}var c={};k=new g(d,f);var i=k.bindEvent;return k.bindEvent=function(a,b,d){"undefined"==typeof d?(d=b,b=c):b=e.mergeArrays(c,b),i.call(this,a,b,d)},k},j=new h,k=new i;b&&m(b.fn),m(HTMLElement.prototype),m(NodeList.prototype),m(HTMLCollection.prototype),m(HTMLDocument.prototype),m(Window.prototype);var n={};return l(j,n,"unbindAllArrive"),l(k,n,"unbindAllLeave"),n}}(window,"undefined"==typeof jQuery?null:jQuery,void 0);
/*
* Map switcher for Strava website.
*
* Copyright © 2016 Tomáš Janoušek.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
var FixScript = document.currentScript;
jQuery.getScript(FixScript.dataset.layersUrl).done(function(){
function tileLayer(l) {
var r = L.tileLayer(l.url, l.opts);
if (l.overlay) {
var o = L.tileLayer(l.overlay.url, l.overlay.opts);
r = L.layerGroup([r, o]);
}
return r;
}
function addLayers(map) {
map.layers.runbikehike = map.createLayer("run-bike-hike");
AdditionalMapLayers.forEach(l => map.layers[l.type] = tileLayer(l));
if (window.google) {
window.google.load("maps", "3.9", {"other_params":"sensor=false&libraries=geometry,places&client=gme-stravainc1", callback: function(){
//'https://cdn.rawgit.com/shramov/leaflet-plugins/master/layer/tile/Google.js'
jQuery.getScript(FixScript.dataset.googleJsUrl).done(function() {
map.layers.googlesatellite = new L.Google('SATELLITE');
map.layers.googleroadmap = new L.Google('ROADMAP');
map.layers.googlehybrid = new L.Google('HYBRID');
map.layers.googleterrain = new L.Google('TERRAIN');
});
}});
}
}
Strava.Maps.Mapbox.Base.mapIds.runbikehike_id = "mapbox.run-bike-hike";
var layerNames =
{terrain: Strava.I18n.Locale.t("strava.maps.google.custom_control.terrain")
,standard: Strava.I18n.Locale.t("strava.maps.google.custom_control.standard")
,satellite: Strava.I18n.Locale.t("strava.maps.google.custom_control.satellite")
,runbikehike: "Run/Bike/Hike"
,googlesatellite: "Google Satellite"
,googleroadmap: "Google Road Map"
,googlehybrid: "Google Hybrid"
,googleterrain: "Google Terrain"
};
AdditionalMapLayers.forEach(l => layerNames[l.type] = l.name);
var activityOpts = jQuery('#map-type-control .options');
if (activityOpts.length) {
Strava.Maps.CustomControlView.prototype.handleMapTypeSelector = function(t) {
var e, i, r;
return(
e = this.$$(t.target),
r = e.data("map-type-id"),
i = this.$("#selected-map").data("map-type-id"),
e.data("map-type-id", i),
e.text(layerNames[i]),
this.$("#selected-map").data("map-type-id", r),
this.$("#selected-map").text(layerNames[r]),
this.changeMapType(r)
);
};
var once = true;
Strava.Maps.Mapbox.CustomControlView.prototype.changeMapType = function(t){
var map = this.map();
if (once) {
once = false;
addLayers(map);
// this is needed for the right handleMapTypeSelector to be called
this.delegateEvents();
}
localStorage.stravaMapSwitcherPreferred = t;
return map.setLayer(t);
};
var optsToAdd = [];
optsToAdd.push(
{type: "runbikehike", name: "Run/Bike/Hike"});
AdditionalMapLayers.forEach(l => optsToAdd.push({type: l.type, name: l.name}));
optsToAdd.push(
{type: "googlesatellite", name: "Google Satellite"},
{type: "googleroadmap", name: "Google Road Map"},
{type: "googlehybrid", name: "Google Hybrid"},
{type: "googleterrain", name: "Google Terrain"});
optsToAdd.forEach(o => activityOpts.append(jQuery('<li>').append(jQuery('<a class="map-type-selector">').data("map-type-id", o.type).text(o.name))));
var preferredMap = localStorage.stravaMapSwitcherPreferred;
// make sure delegateEvents is run at least once
activityOpts.find(':first a').click();
activityOpts.removeClass("open-menu");
activityOpts.parent().removeClass("active");
// select preferred map type
if (preferredMap) {
var mapLinks = activityOpts.find('a.map-type-selector');
mapLinks.filter((_, e) => jQuery(e).data("map-type-id") === preferredMap).click();
activityOpts.removeClass("open-menu");
activityOpts.parent().removeClass("active");
}
}
var explorerMapFilters = jQuery('#segment-map-filters form');
if (explorerMapFilters.length) {
var once = false;
function explorerFound(e) {
if (once)
return;
once = true;
addLayers(e.map);
function setMapType(t) {
localStorage.stravaMapSwitcherSegmentExplorerPreferred = t;
e.map.setLayer(t);
}
var nav = jQuery('#segment-map-filters');
nav.css({height: 'auto'});
var clr = jQuery('<div>');
clr.css({clear: 'both', "margin-bottom": '1em'});
nav.append(clr);
function addButton(name, type) {
var b = jQuery("<div class='button btn-xs'>").text(name);
b.click(() => { setMapType(type); });
clr.append(b);
}
addButton("Standard", "standard");
addButton("Terrain", "terrain");
addButton("Satellite", "satellite");
addButton("Run/Bike/Hike", "runbikehike");
AdditionalMapLayers.forEach(l => addButton(l.name, l.type));
addButton("Google Satellite", "googlesatellite");
addButton("Google Road Map", "googleroadmap");
addButton("Google Hybrid", "googlehybrid");
addButton("Google Terrain", "googleterrain");
var preferredMap = localStorage.stravaMapSwitcherPreferred;
if (preferredMap) {
setTimeout(() => { setMapType(preferredMap); });
}
}
var old_navigate = Strava.Explorer.Navigation.prototype.navigate;
Strava.Explorer.Navigation.prototype.navigate = function(){
old_navigate.call(this);
explorerFound(this.explorer);
Strava.Explorer.Navigation.prototype.navigate = old_navigate;
};
explorerMapFilters.trigger('submit');
}
var routeBuilderOpts = jQuery('#view-options li.map-style div.switches');
if (routeBuilderOpts.length) {
var once = true;
Strava.Routes.MapViewOptionsView.prototype.setMapStyle = function(t){
var map = this.map;
if (once) {
once = false;
addLayers(map);
}
localStorage.stravaMapSwitcherPreferred = t;
return map.setLayer(t);
};
var preferredMap = localStorage.stravaMapSwitcherPreferred;
// change map so that our setMapStyle is called
routeBuilderOpts.find('div:last').click();
routeBuilderOpts.css({display: 'block', position: 'relative'});
AdditionalMapLayers.forEach(l =>
routeBuilderOpts.append(
jQuery("<div class='button btn-xs' tabindex='0'>").data("value", l.type).text(l.name)
)
);
routeBuilderOpts.children().css({display: 'block', width: '100%'});
if (preferredMap) {
routeBuilderOpts.children().filter((_, e) => jQuery(e).data("value") === preferredMap).click();
}
}
});
// https://github.com/shramov/leaflet-plugins/blob/master/layer/tile/Google.js
// MIT licensed
/*
* Google layer using Google Maps API
*/
/* global google: true */
L.Google = L.Class.extend({
includes: L.Mixin.Events,
options: {
minZoom: 0,
maxZoom: 18,
tileSize: 256,
subdomains: 'abc',
errorTileUrl: '',
attribution: '',
opacity: 1,
continuousWorld: false,
noWrap: false,
mapOptions: {
backgroundColor: '#dddddd'
}
},
// Possible types: SATELLITE, ROADMAP, HYBRID, TERRAIN
initialize: function (type, options) {
L.Util.setOptions(this, options);
this._ready = google.maps.Map !== undefined;
if (!this._ready) L.Google.asyncWait.push(this);
this._type = type || 'SATELLITE';
},
onAdd: function (map, insertAtTheBottom) {
this._map = map;
this._insertAtTheBottom = insertAtTheBottom;
// create a container div for tiles
this._initContainer();
this._initMapObject();
// set up events
map.on('viewreset', this._reset, this);
this._limitedUpdate = L.Util.limitExecByInterval(this._update, 150, this);
map.on('move', this._update, this);
map.on('zoomanim', this._handleZoomAnim, this);
//20px instead of 1em to avoid a slight overlap with google's attribution
map._controlCorners.bottomright.style.marginBottom = '20px';
this._reset();
this._update();
},
onRemove: function (map) {
map._container.removeChild(this._container);
map.off('viewreset', this._reset, this);
map.off('move', this._update, this);
map.off('zoomanim', this._handleZoomAnim, this);
map._controlCorners.bottomright.style.marginBottom = '0em';
},
getAttribution: function () {
return this.options.attribution;
},
setOpacity: function (opacity) {
this.options.opacity = opacity;
if (opacity < 1) {
L.DomUtil.setOpacity(this._container, opacity);
}
},
setElementSize: function (e, size) {
e.style.width = size.x + 'px';
e.style.height = size.y + 'px';
},
_initContainer: function () {
var tilePane = this._map._container,
first = tilePane.firstChild;
if (!this._container) {
this._container = L.DomUtil.create('div', 'leaflet-google-layer leaflet-top leaflet-left');
this._container.id = '_GMapContainer_' + L.Util.stamp(this);
this._container.style.zIndex = 'auto';
}
tilePane.insertBefore(this._container, first);
this.setOpacity(this.options.opacity);
this.setElementSize(this._container, this._map.getSize());
},
_initMapObject: function () {
if (!this._ready) return;
this._google_center = new google.maps.LatLng(0, 0);
var map = new google.maps.Map(this._container, {
center: this._google_center,
zoom: 0,
tilt: 0,
mapTypeId: google.maps.MapTypeId[this._type],
disableDefaultUI: true,
keyboardShortcuts: false,
draggable: false,
disableDoubleClickZoom: true,
scrollwheel: false,
streetViewControl: false,
styles: this.options.mapOptions.styles,
backgroundColor: this.options.mapOptions.backgroundColor
});
var _this = this;
this._reposition = google.maps.event.addListenerOnce(map, 'center_changed',
function () { _this.onReposition(); });
this._google = map;
google.maps.event.addListenerOnce(map, 'idle',
function () { _this._checkZoomLevels(); });
google.maps.event.addListenerOnce(map, 'tilesloaded',
function () { _this.fire('load'); });
//Reporting that map-object was initialized.
this.fire('MapObjectInitialized', {mapObject: map});
},
_checkZoomLevels: function () {
//setting the zoom level on the Google map may result in a different zoom level than the one requested
//(it won't go beyond the level for which they have data).
// verify and make sure the zoom levels on both Leaflet and Google maps are consistent
if ((this._map.getZoom() !== undefined) && (this._google.getZoom() !== this._map.getZoom())) {
//zoom levels are out of sync. Set the leaflet zoom level to match the google one
this._map.setZoom(this._google.getZoom());
}
},
_reset: function () {
this._initContainer();
},
_update: function () {
if (!this._google) return;
this._resize();
var center = this._map.getCenter();
var _center = new google.maps.LatLng(center.lat, center.lng);
this._google.setCenter(_center);
if (this._map.getZoom() !== undefined)
this._google.setZoom(Math.round(this._map.getZoom()));
this._checkZoomLevels();
},
_resize: function () {
var size = this._map.getSize();
if (this._container.style.width === size.x &&
this._container.style.height === size.y)
return;
this.setElementSize(this._container, size);
this.onReposition();
},
_handleZoomAnim: function (e) {
var center = e.center;
var _center = new google.maps.LatLng(center.lat, center.lng);
this._google.setCenter(_center);
this._google.setZoom(Math.round(e.zoom));
},
onReposition: function () {
if (!this._google) return;
google.maps.event.trigger(this._google, 'resize');
}
});
L.Google.asyncWait = [];
L.Google.asyncInitialize = function () {
var i;
for (i = 0; i < L.Google.asyncWait.length; i++) {
var o = L.Google.asyncWait[i];
o._ready = true;
if (o._container) {
o._initMapObject();
o._update();
}
}
L.Google.asyncWait = [];
};
/*
* Map switcher for Strava website.
heatmap
https://heatmap-external-c.strava.com/tiles-auth/{all,ride,run,water,winter}/{hot,blue,gray,bluered}/{z}/{x}/{y}.png?v=19
example =>
https://heatmap-external-b.strava.com/tiles-auth/ride/hot/{z}/{x}/{y}.png?v=19
*/
var AdditionalMapLayers = (function(){
var osmAttr = '&copy; <a href="http://openstreetmap.org" target="_blank">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/" target="_blank">CC-BY-SA</a>';
var thunderforestAttr = osmAttr + ', Tiles courtesy of <a href="http://www.thunderforest.com/" target="_blank">Andy Allan</a>';
var mtbMapAttr = osmAttr + ', Tiles courtesy of <a href="http://mtbmap.cz/" target="_blank">mtbmap.cz</a>';
var mapyCzAttr = '&copy; <a href="https://www.seznam.cz/" target="_blank">Seznam.cz, a.s</a>, ' + osmAttr;
var cuzkAttr = '&copy; <a href="http://geoportal.cuzk.cz" target="_blank">ČÚZK</a>';
return [
{
type: "marshruty",
name: "marshruty_ru",
url: "https://maps.marshruty.ru/ml.ashx?x={x}&y={y}&z={z}&i=1&al=1",
opts: { maxZoom: 20, attribution: '' }
},
{
type: "openstreetmap",
name: "OpenStreetMap",
url: "http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
opts: { maxZoom: 20, maxNativeZoom: 19, attribution: '' }
},
{
type: "2gis",
name: "2gis_ru",
url: "https://tile0.maps.2gis.com/tiles?x={x}&y={y}&z={z}&v=1.3",
opts: { maxZoom: 20, attribution: '2gis' }
},
{
type: "runkeeper",
name: "RunKeeper",
url: "https://api.mapbox.com/v4/runkeeper.4nc7syvi/{z}/{x}/{y}.png?access_token=pk.eyJ1Ijoia2FzaGFldiIsImEiOiJjaW5hcWF1a2gwMDJjdzRseGU1OW5qanAyIn0.GS3Ml73n10hf7ZSgcnlSzw",
opts: { maxZoom: 20, attribution: thunderforestAttr }
},
//
// {
// type: "heatmapride",
// name: "Heatmap - Bicycle",
// url: "https://heatmap-external-b.strava.com/tiles-auth/ride/hot/{z}/{x}/{y}.png?v=19",
// opts: { maxZoom: 20, attribution: thunderforestAttr }
// },
//
// {
// type: "mapycz",
// name: "mapy.cz",
// url: "https://mapserver.mapy.cz/turist-m/{z}-{x}-{y}",
// opts: {
// minZoom: 2,
// maxZoom: 20,
// maxNativeZoom: 18,
// attribution: mapyCzAttr
// }
// }
];
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment