Skip to content

Instantly share code, notes, and snippets.

@iamdey
Forked from herejia/leboncoin-distance.user.js
Last active May 13, 2016 08:30
Show Gist options
  • Save iamdey/e5cda189ac53654c2499d0ce7ff1bb0c to your computer and use it in GitHub Desktop.
Save iamdey/e5cda189ac53654c2499d0ce7ff1bb0c to your computer and use it in GitHub Desktop.
// ==UserScript==
// @name leboncoin-distance
// @namespace net.herezia
// @description Affiche la distance en mn et km avec le lieu d'une offre
// @include https://*.leboncoin.fr/*/offres/*
// @version 3
// @grant GM_getValue
// @grant GM_setValue
// ==/UserScript==
const DEFAULT_FETCH_OPTIONS = {
method: 'GET',
mode: 'cors',
cache: 'force-cache'
};
const DEFAULT_PLACE = {
name: 'Lyon',
longitude: '4.8324803',
latitude: '45.7575286'
};
const LOCATION_NAME_KEY = 'fromLocationName';
const LONGITUDE_KEY = 'fromLocationLongitude';
const LATITUDE_KEY = 'fromLocationLatitude';
const coordinates = {
getLongitude: function() {
return GM_getValue(LONGITUDE_KEY) || DEFAULT_PLACE.longitude;
},
setLongitude: function(lon) {
GM_setValue(LONGITUDE_KEY, lon);
document.querySelector('#start-location-longitude').value = lon;
return this;
},
getLatitude: function() {
return GM_getValue(LATITUDE_KEY) || DEFAULT_PLACE.latitude;
},
setLatitude: function(lat) {
GM_setValue(LATITUDE_KEY, lat);
document.querySelector('#start-location-latitude').value = lat;
return this;
}
};
function insertUI() {
var startLocationHtml = '<div class="from-location">' +
' <fieldset><legend>Afficher les distances</legend>' +
' <input id="start-location-city" placeholder="Ville" type="text"/><input value="☉" title="Géolocaliser" id="geolocate-button" type="button"/>' +
' <input id="start-location-longitude" placeholder="Longitude" type="text"/>' +
' <input id="start-location-latitude" placeholder="Latitude" type="text"/>' +
' </fieldset>' +
'</div>';
document.querySelector('.location-container').innerHTML += startLocationHtml;
Array.from(document.querySelectorAll('.item_infos')).forEach(detailDiv => {
detailDiv.insertAdjacentHTML("afterbegin", '<div class="hrz-distance" style="float: right"></div>');
});
function bindInputToGMValue(inputSelector, gmValueKey, defaultValue) {
var input = document.querySelector(inputSelector);
input.value = GM_getValue(gmValueKey) || defaultValue;
input.addEventListener('change', function() {
GM_setValue(gmValueKey, input.value);
});
}
bindInputToGMValue('#start-location-city', LOCATION_NAME_KEY, DEFAULT_PLACE.name);
bindInputToGMValue('#start-location-longitude', LONGITUDE_KEY, DEFAULT_PLACE.longitude);
bindInputToGMValue('#start-location-latitude', LATITUDE_KEY, DEFAULT_PLACE.latitude);
const cityInput = document.querySelector('#start-location-city');
cityInput.addEventListener('change', function() {
getCoordinates(cityInput.value).then(city => {
coordinates.setLongitude(city.lon).setLatitude(city.lat);
return showDistances();
});
});
document.querySelector('#geolocate-button').addEventListener('click', function() {
navigator.geolocation.getCurrentPosition(
position => {
const coords = position.coords;
cityInput.value = 'Ma position';
GM_setValue(LOCATION_NAME_KEY, cityInput.value);
coordinates.setLatitude(coords.latitude).setLongitude(coords.longitude);
showDistances();
},
() => alert('Localisation impossible'));
});
}
function getDistance(destinationLon, destinationLat) {
//var distanceUrl = 'http://api-osrm-routed-production.tilestream.net/viaroute?output=json&z=14'
// https://api-osrm-routed-production.tilestream.net or https://router.project-osrm.org
const distanceUrl = 'https://router.project-osrm.org/viaroute?z=14'
+ '&loc=' + coordinates.getLatitude() + ',' + coordinates.getLongitude()
+ '&loc=' + destinationLat + ',' + destinationLon;
return fetch(distanceUrl, DEFAULT_FETCH_OPTIONS)
.then(function(response) {
return response.json();
})
.then(function(json) {
return {
time: Math.round(json.route_summary.total_time / 60),
distance: Math.round(json.route_summary.total_distance / 1000)
};
});
}
function getCoordinates(locationName) {
var locationByNameUrl = 'https://nominatim.openstreetmap.org/search?q=' + encodeURI(locationName) + '&format=json';
return fetch(locationByNameUrl, DEFAULT_FETCH_OPTIONS)
.then(response => response.json())
.then(json => json[0]);
}
function fillHrzItem(itemSection, text) {
const distanceHolder = itemSection.querySelector('.hrz-distance');
distanceHolder.innerHTML = text;
}
function showDistances() {
Array.from(document.querySelectorAll('.item_infos')).forEach(function(itemSection) {
const placementDiv = itemSection.querySelectorAll('.item_supp')[1];
const cityLocation = placementDiv.innerHTML;
const cityName = cityLocation.replace(/\s/gm, '').replace('/', ', ');
getCoordinates(cityName)
.then(function(city) {
if (!city) {
return Promise.reject('introuvable');
}
return getDistance(city.lon, city.lat)
.then(travelData => {
fillHrzItem(itemSection, '⌚ ' + travelData.time + ' mn ⛟ ' + travelData.distance + 'km');
});
})
.catch(function(err) {
fillHrzItem(itemSection, 'échec :' + err);
});
});
}
insertUI();
showDistances();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment