In: Computer Science
Following is the activity of javascript. i have tried to do it but got stuck from question 3, I have also attached my javascript code right after the HTML file. can you please help me. Inside the java script code, it contains all the necessary token. if you run the html file, it will display longitude as a AQI so need to fix that.
Web Services Activity (1%)
You need to sign up to the API to obtain a key/token at WAQI API [link]
You should save the files as w9-webservices.js and w9-webservices.html
We would like to display the AQI information around the current user's geoposition on a map.
Instructions:
AQI range |
Colour |
0 -- 50 |
Green |
51 -- 100 |
Yellow |
101 -- 150 |
Orange |
151 -- 200 |
Red |
201 -- 300 |
Purple |
301 -- 500 |
Maroon |
map.on('zoomend',function(){ // run some code if the zoom changes });When the user changes the zoom (and thus the map boundaries change), you should update the map information by running (3) -> (5) again.
Notes:
Here's some code to get you started with the HTML page:
<html> <head> <meta charset="utf-8"> <title>Week 9 Web Services Activity</title> <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" /> <!-- Import MDL libraries --> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.indigo-pink.min.css"> <script defer src="https://code.getmdl.io/1.3.0/material.min.js"></script> <!-- Import Mapbox libraries --> <script src="https://api.mapbox.com/mapbox-gl-js/v1.7.0/mapbox-gl.js"></script> <link href="https://api.mapbox.com/mapbox-gl-js/v1.7.0/mapbox-gl.css" rel="stylesheet" /> <style> /* Define any CSS here */ #map { width: 80vw; height: 80vh } </style> </head> <body> <div class="mdl-layout mdl-js-layout mdl-layout--fixed-header"> <header class="mdl-layout__header"> <div class="mdl-layout__header-row"> <span class="mdl-layout__title">Check the air quality on the map</span> </div> </header> <main class="mdl-layout__content"> <div class="mdl-grid"> <div class="mdl-cell mdl-cell--8-col"> <!-- Map div --> <div id='map'> </div> </div> </div> </main> </div> <script src="w9-webservices.js"></script> </body> </html>
w9-webservices.js
"use strict";
// mapbox token
const MAPBOX_TOKEN = "pk.eyJ1IjoidGVlZSIsImEiOiJja2c2ODQ0cHQxMXUwMnJsZDJyOTY5YXRvIn0.0yh14c1R35E-dxvvAC1nxw";
// WAQI token
const WAQI_TOKEN = "4e4ff5b84906529e3768ed72754304c9057587c1";
navigator.geolocation.getCurrentPosition((position) => {
doSomething(position.coords.latitude, position.coords.longitude);
});
function doSomething(lat,lng){
console.log(lat,lng);
mapboxgl.accessToken = MAPBOX_TOKEN;
let map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v9', // stylesheet location
center: [lng,lat], // starting position [lng, lat]
zoom: 13 // starting zoom
}) ;
map.setCenter([lng,lat]);
let marker = new mapboxgl.Marker({ "color": "#FF8C00" });
marker.setLngLat([lng,lat]);
let popup = new mapboxgl.Popup({ offset: 45});
let desc = `AQI: ${lng}`; // at the moment i have just used AQI value as a lngitude.
popup.setHTML(desc);
marker.setPopup(popup)
marker.addTo(map);
popup.addTo(map);
}
Hello There!
Here is the solution for your js activity.
Hope it helps!
Thumbsup ;)
w9-webservices.html
<html>
<head>
<meta charset="utf-8" />
<title>Week 9 Web Services Activity</title>
<meta
name="viewport"
content="initial-scale=1,maximum-scale=1,user-scalable=no"
/>
<!-- Import MDL libraries -->
<link
rel="stylesheet"
href="https://fonts.googleapis.com/icon?family=Material+Icons"
/>
<link
rel="stylesheet"
href="https://code.getmdl.io/1.3.0/material.indigo-pink.min.css"
/>
<script defer src="https://code.getmdl.io/1.3.0/material.min.js"></script>
<!-- Import Mapbox libraries -->
<script src="https://api.mapbox.com/mapbox-gl-js/v1.7.0/mapbox-gl.js"></script>
<link
href="https://api.mapbox.com/mapbox-gl-js/v1.7.0/mapbox-gl.css"
rel="stylesheet"
/>
<style>
/* Define any CSS here */
#map {
width: 80vw;
height: 80vh;
}
#marker {
width: 18px;
height: 18px;
border-radius: 30%;
cursor: pointer;
}
.mapboxgl-popup {
max-width: 200px;
}
</style>
</head>
<body>
<div class="mdl-layout mdl-js-layout mdl-layout--fixed-header">
<header class="mdl-layout__header">
<div class="mdl-layout__header-row">
<span class="mdl-layout__title"
>Check the air quality on the map</span
>
<h5 id="error" style="background-color: brown"></h5>
</div>
</header>
<main class="mdl-layout__content">
<div class="mdl-grid">
<div class="mdl-cell mdl-cell--8-col">
<!-- Map div -->
<div id="map"></div>
</div>
</div>
</main>
</div>
<script src="w9-webservices.js"></script>
</body>
</html>
w9-webservices.js
var x = document.getElementById("error");
var lat;
var lon;
getLocation(); //calling the function initially
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "some error occured in the browser.";
}
}
//callback function for above function
function showPosition(position) {
//setting map with current location
lat = position.coords.latitude;
lon = position.coords.longitude;
console.log(lat, lon);
mapboxgl.accessToken =
"pk.eyJ1IjoibmlraGlsbmFnYXIiLCJhIjoiY2tnZXM3MzUxMGNvaDJxcGZiMm01MWo1aiJ9.wKjHS-PJlAUmlItq5X9M2w";
var map = new mapboxgl.Map({
container: "map",
style: "mapbox://styles/mapbox/streets-v11",
center: [lon, lat],
zoom: 5,
});
//adding current location popup
var popup = new mapboxgl.Popup({ offset: 5 }).setText("Your Location");
var marker = new mapboxgl.Marker()
.setLngLat([lon, lat])
.setPopup(popup)
.addTo(map);
//getting bounds
var bounds = map.getBounds();
bounds =
bounds.getNorth() +
"," +
bounds.getWest() +
"," +
bounds.getSouth() +
"," +
bounds.getEast();
console.log(bounds);
//calling function to populate markers on tha map from api data
populateMarkers(bounds);
function populateMarkers(bounds) {
//api request
fetch(
"https://api.waqi.info/map/bounds/?latlng=" +
bounds +
"&token=" +
"fb5964fcfc03f43640925ebfcee05d3fd81376ff"
)
.then((x) => x.json())
.then((stations) => {
console.log(stations);
if (stations.status != "ok") throw stations.reason;
//looping through each station.
stations.data.forEach((station) => {
var coordinates = [station.lon, station.lat];
var name = station.station["name"];
var aqi = station["aqi"];
var info = `Name: ${name} \nAQI: ${aqi}\nCoordinates: ${coordinates}`;
var popup = new mapboxgl.Popup({ offset: 5 }).setText(info);
//setting marker color according to aqi value.
var color;
var value = parseInt(aqi);
if (value === NaN) {
color = "white";
} else if (value > 0 && value <= 50) {
color = "green";
} else if (value >= 51 && value <= 100) {
color = "yellow";
} else if (value >= 101 && value <= 150) {
color = "orange";
} else if (value >= 151 && value <= 200) {
color = "red";
} else if (value >= 201 && value <= 300) {
color = "purple";
} else if (value >= 301 && value <= 500) {
color = "maroon";
}
// create DOM element for the marker
var el = document.createElement("div");
el.id = "marker";
el.style.background = color;
// create the marker
new mapboxgl.Marker(el)
.setLngLat(coordinates)
.setPopup(popup) // sets a popup on this marker
.addTo(map);
//when zoom will be changed, it will restart the process.
map.on('zoomend',function(){
console.log("Zoom changed!");
//getting bounds
var bounds = map.getBounds();
bounds =
bounds.getNorth() +
"," +
bounds.getWest() +
"," +
bounds.getSouth() +
"," +
bounds.getEast();
console.log(bounds);
populateMarkers(bounds);
});
});
});
}
}