Question

In: Computer Science

Following is the activity of javascript. i have tried to do it but got stuck from...

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:

  1. When the page loads, get the user's current location using the Geolocation API's getCurrentPosition method. You should use a callback function.
    Display an appropriate error message as required if geolocation fails to get a position.
  2. In the callback function from (1), you should display a map centered at the current coordinates, with an appropriate zoom level.
  3. Obtain the map coordinate boundaries using MapBox's map.getBounds() method.
  4. Using the map boundary data, make a call to the AQI Map Query API [link: https://aqicn.org/json-api/doc/#api-Map_Queries-GetMapStations ] . You should use a callback function for this API call. The URL (with query string and :placeholders) looks like this: https://api.waqi.info/map/bounds/?token=:token&latlng=:latlng&callback=:callback
  5. In the callback function from (4), display a Marker and associated Popup for each location within the boundary coordinate data from (3). If no data is returned, display an appropriate error message.

    You should ensure that the Marker used is of an appropriate color depending on the AQI value (see table below).

    The Popup should display the AQI value and the station name in plain black text.

    AQI range

    Colour

    0 -- 50

    Green

    51 -- 100

    Yellow

    101 -- 150

    Orange

    151 -- 200

    Red

    201 -- 300

    Purple

    301 -- 500

    Maroon

  6. We can detect when the user changes the zoom level using:
    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:

  • You can add CSS inline or to the header section

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);

}

Solutions

Expert Solution

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);

          });
        });
      });
  }
}

Related Solutions

Answer in C++ language please** I got stuck. How do I find the Overall Average,Overall Highest...
Answer in C++ language please** I got stuck. How do I find the Overall Average,Overall Highest number, and the Overall Lowest Number after all of this?? #include <iostream> #include <fstream> #include <iomanip> #include <string> using namespace std; const int ALIASFILE_LINE_COUNT =16; const float USERBONUSLEVEL = 75.09; const float USERAWARDLEVEL = 80.72; const int USERBONUS = 5; const int USERAWARD = 8; void selectionSortAsc( double list[], int length); int main() {cout <<"\n\nproject 3 template,.. \n ,...includes global constants for project.\n"<<endl; //1....
I cant not seem to get this right. I have tried and tried can I please...
I cant not seem to get this right. I have tried and tried can I please get help. Thank you! Writing a Modular Program in Java Summary In this lab, you add the input and output statements to a partially completed Java program. When completed, the user should be able to enter a year, a month, and a day to determine if the date is valid. Valid years are those that are greater than 0, valid months include the values...
Hello! I am stuck on only B-1 Recession EPS - I got everything else and I...
Hello! I am stuck on only B-1 Recession EPS - I got everything else and I cannot figure out what I'm doing wrong - I keep getting $4.81, but it's incorrect and I don't know why. Can you help? I pasted my numbers below the question. Sunrise, Inc., has no debt outstanding and a total market value of $240,900. Earnings before interest and taxes, EBIT, are projected to be $40,000 if economic conditions are normal. If there is strong expansion...
Previous time I tried this problem, I got the answer wrong. The Muse Co. just issued...
Previous time I tried this problem, I got the answer wrong. The Muse Co. just issued a dividend of $3.64 per share on its common stock. The company is expected to maintain a constant 6.44 percent growth rate in its dividends indefinitely. If the stock sells for $62 a share, what is the company's cost of equity? (Enter your answer as a percentage, omit the "%" sign in your response, and round your answer to 2 decimal places. For example,...
I got to the part in bold and I have no idea where to go from...
I got to the part in bold and I have no idea where to go from here. Step 1:Find the pair with the smallest distance. Step 2:Join them in one group and draw those branches. Step 3:Compute average distance between this group and all other taxa one-by-one and create new table with those values. Step 4:Repeat Steps 1 to 3 using the new distance matrix. Characters A B C D E F G A - B 12 - C 8...
Hello, I Have create this code and Tried to add do while loop but it gives...
Hello, I Have create this code and Tried to add do while loop but it gives me the error in string answar; and the areas where I blod So cloud you please help me to do ( do while ) in this code. // Program objective: requires user to input the data, program runs through the data,calcualtes the quantity, chacks prices for each iteam intered,calautes the prices seperatly for each item, and calculates the amount due without tax, and then...
I tried this sight before to find filtering options and got fantastic results, so let's try...
I tried this sight before to find filtering options and got fantastic results, so let's try again! I am setting up an experiment that requires light of two different frequencies (445nm and 350nm). The light ultimately needs to be focused on a small area. I can think of two good ways to make this happen: Get a broad spectrum light source that emits over this range - maybe a halogen lamp? - and buy two filters: A high pass that...
I have tried to answer the following questions. Please let me know if I missed one...
I have tried to answer the following questions. Please let me know if I missed one and why. 1) A light car and a heavy car are headed toward each other from opposite directions at the same speed. The ground is level. Which of the two will be harder to stop? the heavier car 2) Instead of stopping the cars, you jump out of the way. The two cars crash head-on. After the crash what do you see? The two...
I NEED JAVASCRIPT PROGRAM Chose an activity that you enjoy. It can be a sport that...
I NEED JAVASCRIPT PROGRAM Chose an activity that you enjoy. It can be a sport that you watch or participate in, collecting, hobbies, etc. Do not use a collection of movies since we have covered that in the assignment. Do not use the same topic as a friend. (If two students that don’t know each other happen to select the same topic, that is fine, since they will naturally have different property names and values.) 1. Select some aspect of...
I don't know if you have the stats for this but I tried to put them...
I don't know if you have the stats for this but I tried to put them in here and it told me this is too long. I do not have Minitab so I would need it in Excel please and thank you so much. It will not let me put all the info in here. Says its too long. Refer to the Baseball 2016 data, which report information on the 30 Major League Baseball teams for the 2016 season. a....
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT