forked from HackerUSA-CE/JS-Making-an-Interactive-Map
-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.js
96 lines (89 loc) · 2.36 KB
/
app.js
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// map object
const myMap = {
coordinates: [],
businesses: [],
map: {},
markers: {},
// build leaflet map
buildMap() {
this.map = L.map('map', {
center: this.coordinates,
zoom: 11,
});
// add openstreetmap tiles
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution:
'© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
minZoom: '15',
}).addTo(this.map)
// create and add geolocation marker
const marker = L.marker(this.coordinates)
marker
.addTo(this.map)
.bindPopup('<p1><b>You are here</b><br></p1>')
.openPopup()
},
// add business markers
addMarkers() {
for (var i = 0; i < this.businesses.length; i++) {
this.markers = L.marker([
this.businesses[i].lat,
this.businesses[i].long,
])
.bindPopup(`<p1>${this.businesses[i].name}</p1>`)
.addTo(this.map)
}
},
}
// get coordinates via geolocation api
async function getCoords(){
const pos = await new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition(resolve, reject)
});
return [pos.coords.latitude, pos.coords.longitude]
}
// get foursquare businesses
async function getFoursquare(business) {
const options = {
method: 'GET',
headers: {
Accept: 'application/json',
Authorization: 'fsq3ATzZbmcGhdeFafr73wZcnJ+LlN6bK+4dh19a7ClS4u8='
}
}
let limit = 5
let lat = myMap.coordinates[0]
let lon = myMap.coordinates[1]
let response = await fetch(`https://api.foursquare.com/v3/places/search?&query=${business}&limit=${limit}&ll=${lat}%2C${lon}`, options)
let data = await response.text()
let parsedData = JSON.parse(data)
let businesses = parsedData.results
return businesses
}
// process foursquare array
function processBusinesses(data) {
let businesses = data.map((element) => {
let location = {
name: element.name,
lat: element.geocodes.main.latitude,
long: element.geocodes.main.longitude
};
return location
})
return businesses
}
// event handlers
// window load
window.onload = async () => {
const coords = await getCoords()
myMap.coordinates = coords
myMap.buildMap()
}
// business submit button
document.getElementById('submit').addEventListener('click', async (event) => {
event.preventDefault()
let business = document.getElementById('business').value
let data = await getFoursquare(business)
myMap.businesses = processBusinesses(data)
myMap.addMarkers()
})