Fapra-OSM-2/static/js/script.js

87 lines
2 KiB
JavaScript

var map = L.map('map').setView([0, 0], 2);
L.tileLayer( 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>',
subdomains: ['a','b','c']
}).addTo( map );
var popup = L.popup();
var fromMarker = L.marker([0,0], {icon: blueIcon});
var toMarker = L.marker([0,0], {icon: greyIcon});
function setFrom(e) {
setField("from");
fromMarker.setLatLng(popup.getLatLng()).addTo(map);
}
function setTo(e) {
setField("to");
toMarker.setLatLng(popup.getLatLng()).addTo(map);
}
function setField(field) {
var latlng = sanitizeLatLng(popup.getLatLng())
document.getElementById(field).value = latlng.lat + "," + latlng.lng;
popup.close()
}
function sanitizeLatLng(latlng){
// "modulo around the world" while keeping the range from -180 to 180
latlng.lng = (((latlng.lng +180) % 360) + 360) % 360 - 180
return latlng
}
function onMapClick(e) {
popup
.setLatLng(e.latlng)
.setContent("<p>Position " + e.latlng + '</p><button class="btn btn-primary" onclick="setFrom()">From</button> <button class="btn btn-secondary" onClick="setTo()">To</button>')
.openOn(map);
}
map.on("click", onMapClick);
let routeObject = L.geoJSON();
async function get_random_route() {
let result = await fetch("/random")
if (result.ok) {
let json = await result.json()
show_route(json)
} else {
alert("an error occured while finding the route");
}
}
function show_route(route){
clear_route();
routeObject = L.geoJSON(route).addTo(map);
}
function clear_route() {
routeObject.remove()
}
function set_route_cost(cost) {
let field = document.getElementById("routecost");
field.value = cost;
}
async function get_route() {
let form = document.getElementById("queryform");
data = new FormData(form);
let response = await(fetch("/route", { method: "POST", body: data }));
let result = await response.json();
if (result.success === true) {
set_route_cost(result.route.cost);
show_route(result.route.geojson);
} else {
set_route_cost(null);
clear_route();
alert("No Route found!");
}
}