summaryrefslogtreecommitdiffstats
path: root/templates/index.js
blob: bc05ed779da70d38a2e31714a8ca6e92ed742002 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
var map;
const form = document.querySelector('#path-form')
const markerIsStart = document.querySelector("#marker-point-start")
const markerIsEnd = document.querySelector("#marker-point-end")

google.maps.event.addDomListener(window, 'load', initialize);
form.addEventListener('submit', postShortestPath, false)


function initialize() {
    var mapOptions = {
        center: new google.maps.LatLng(58.40384776751319, 15.578484535217285),
        zoom: 15,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var mapCanvas = document.getElementById("map_canvas")
    map = new google.maps.Map(mapCanvas, mapOptions);
    google.maps.event.addListener(map, 'click', handleMapClick)
}

async function postShortestPath(event){
    event.preventDefault()
    var lat1 = parseFloat(document.querySelector('#lat1').value)
    var lng1 = parseFloat(document.querySelector('#lng1').value)
    var lat2 = parseFloat(document.querySelector('#lat2').value)
    var lng2 = parseFloat(document.querySelector('#lng2').value)

    // Check that they're not Nan (stops function if one is Nan)
    if(!lat1 || !lng1  || !lat2 || !lng2)
        return alert('Formatting Error: Coordinates are not float values.')
    
    req = {lat1, lng1, lat2, lng2} // Dictionary auto-keys

    res = await fetch('/shortest-path', {
        method:'POST',
        credentials: 'same-origin',
        body: JSON.stringify(req)
    })

    res = await res.json() 
    var points = new google.maps.MVCArray()
    console.log(res.path)
    res.path.map(coord=>{
        var [lat, lng] = coord
        var point = new google.maps.LatLng(lat, lng)
        points.push(point)
    })

    createPolyline(points)
}

function createPolyline(points){
    var polyline = new google.maps.Polyline({
        path: points,
        map: map
    });
}

function handleMapClick ({latLng}){
    createMarker(latLng, `Click: ${latLng}`)
    console.log(latLng)
    var {lat, lng} = latLng 
    var posNumber = markerIsStart.checked ? '1' : '2'
    document.querySelector('#lat' + posNumber).value = lat()
    document.querySelector('#lng' + posNumber).value = lng()
    if(markerIsStart.checked)
        markerIsEnd.checked = true 
    

}


function createMarker (position, title){
    return new google.maps.Marker({
        map,
        position,
        title
    })
}