wunderground compass tool indicating the direction of the wind

I am using weather jQuery from the Wunderground API, and my jQuery is working well. However, the problem lies in the Wunderground API wind direction degrees. I want to display the wind degrees on a compass, and I found this answer on StackOverflow:

CSS:

#compass {
  width: 380px;
  height: 380px;
  background-image:url('http://i.imgur.com/44nyA.jpg');
  position: relative;
}
#arrow {
  width: 360px;
  height: 20px;
  background-color:#F00;
  position: absolute;
  top: 180px;
  left: 10px;
  -webkit-transform:rotate(120deg);
  -moz-transform:rotate(120deg);
  -o-transform:rotate(120deg);
  -ms-transform:rotate(120deg);

  -moz-transition: all 1s ease;
  -webkit-transition: all 1s ease;
  -o-transition: all 1s ease;
  transition: all 1s ease;
}

#compass:hover #arrow {
  -webkit-transform:rotate(0deg);
  -moz-transform:rotate(0deg);
  -o-transform:rotate(0deg);
  -ms-transform:rotate(0deg);
}​

HTML:

<div id="compass">
  <div id="arrow"></div>
</div>​

I want to implement this CSS in my jQuery weather application, but I'm not sure how. Here is a demo of this CSS: http://jsfiddle.net/adb2A/

This is my jQuery code:

 var x = document.getElementById("demo");

 if (navigator.geolocation) {
 navigator.geolocation.getCurrentPosition(showPosition);
 } else { 
 x.innerHTML = "Geolocation is not supported by this browser.";
 }

 function showPosition(position) {
 var location = position.coords.latitude + "," + position.coords.longitude; 

 jQuery(document).ready(function(weather) {

 $.ajax({
 url : "http://api.wunderground.com/api/eb7a37c339cfd624/geolookup/conditions/forecast10day/lang:AR/q/"+location+".json",
 dataType : "jsonp",
success : function(data) {


var html = '<div style="color: black;text-align:right;direction: rtl;">';

html += '<h2>Current Temperature: ' + data.current_observation.temp_c + '</h2>'
html += '<h3>Feels Like: ' + data.current_observation.feelslike_c + '</h3>'
html += '<h3>Humidity: ' + data.current_observation.relative_humidity + '</h3>'
html += '<h3>Atmospheric Pressure: ' + data.current_observation.pressure_mb + '</h3>'
html += '<h3>Today\'s Precipitation: ' + data.current_observation.precip_today_in + '</h3>'

html += '</div>';

  $("#news").append(html).hide().fadeIn("slow");

  ///10-day Forecast///

var dayArray = data.forecast.txt_forecast['forecastday'];

var html = '<div id="10days" style="color: black;text-align:right;direction: rtl;">';
for(var i=0; i<dayArray.length; i+=2)

html += '<div class="container center-block"><div class="row "><div class="col-md-8 col-md-offset-2"><h3>'+data.forecast.txt_forecast.forecastday[i]['title']+ " : " +data.forecast.txt_forecast.forecastday[i]['fcttext_metric']+'</h3></div>'

html += '</div></div>';

  $("#10").append(html).hide().fadeIn("slow");


 }
 });
 });
 } 

Answer №1

UPDATE 2021: The provided code example is no longer functional due to the deprecation of the Weather Underground (Wunderground) API in 2018. Nevertheless, it can be adjusted to utilize a different data provider.

Creating a Custom Dial Gauge

This guide outlines the process of constructing a custom dial gauge for displaying wind direction information. By following this code snippet, you can develop a professional-looking gauge with minimal coding effort. It's easily customizable for various applications and datasets.

The original poster attempted to achieve this using a complex CSS transformation method. However, a simpler approach involves utilizing the CANVAS tag along with a scaled background image and a dynamically positioned indicator needle.

Below is the basic code structure required. With additional styling details as demonstrated in the complete code snippet, you can produce a sleek dial gauge suitable for any project.

Experience the Demo

To observe the demo, click on "Show code snippet" and then "Run code snippet" (you may need to scroll down). The demo showcases the current wind direction in Berlin, Germany. Click the "test" button to animate the gauge.

CSS

#compass {
  background: url(YourGaugeBackground.jpg); 
  background-size: cover;
}

Javascript:

function setCompass(degrees) {
      var x, y, r, ctx, radians;
      ctx = window.compass.getContext("2d");
      radians = 0.0174533 * (degrees - 90);
      x = ctx.canvas.width / 2;
      y = ctx.canvas.height / 2; 
      ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height );
      ctx.beginPath();
      ctx.lineWidth = 10;
      ctx.moveTo(x, y);
      ctx.lineTo(x + r * Math.cos(radians), y + r * Math.sin(radians));
      ctx.stroke();
}

HTML

<canvas id="compass" height=200 width=200></canvas>

// JavaScript function for adjusting compass position based on degrees
function setCompass(degrees) {

  var x, y, r, ctx, radians;
  
  ctx = window.compass.getContext("2d");
  
  // Subtracts 90 to orient north correctly and converts to radians
  radians = 0.0174533 * (degrees - 90);
  
  // Calculates compass center coordinates
  x = ctx.canvas.width / 2;
  y = ctx.canvas.height / 2; 
  r = x * 0.8;
  
  // Clears canvas
  ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height );
  ctx.beginPath();

  // Optional styling features
  ctx.strokeStyle = "rgba(255,0,0,0.5)";
  ctx.fillStyle = "rgba(255,0,0,0.5)";
  ctx.lineCap = 'round';
  ctx.shadowOffsetX = 4;
  ctx.shadowOffsetY = 4;
  ctx.shadowBlur = 2;
  ctx.shadowColor = "rgba(0, 0, 0, 0.5)";

  // Draws the compass needle
  ctx.lineWidth = 10;
  ctx.moveTo(x, y);
  ctx.lineTo(x + r * Math.cos(radians), y + r * Math.sin(radians));
  ctx.stroke();

}

// Ajax call for retrieving city weather data
function getWeatherForecast() {

  var url = 'http://api.wunderground.com/api/eb7a37c339cfd624/geolookup/conditions/forecast10day/lang:EN/q/Germany/Berlin.json';

  $.getJSON(url, function(data) {
    window.debug.innerHTML = JSON.stringify(data, false, '  ');
    $('#status').html(
      //'<img src="' + data.current_observation.icon_url + '">' +
      data.location.city + ', ' +
      data.location.country_name + ': ' +
      data.current_observation.temperature_string + ', ' +
      'Wind ' +
      data.current_observation.wind_string + ', ' +
      data.current_observation.wind_degrees + '°'
    );
    setCompass(data.current_observation.wind_degrees);
  });

}

$('#test').click(function() {
  $(this).attr('disabled', true);
  var d=0, id = setInterval(function() {
    setCompass( d );
    d += 10;
    if (d > 360) {
      clearInterval(id);
      $('#test').attr('disabled',false);
      getWeatherForecast();
    }
  }, 100);
  
});


$(document).ready(function() {
  getWeatherForecast();
});
#compass {
  background: url(http://i.imgur.com/44nyA.jpg);
  background-size: cover;
}

body {
  font-family: sans-serif;
}

#debug {
  background-color: aliceblue;
  border: 1px solid black;
  padding: 0.5em;
  width: 90%;
  height: 50em;
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


<button id="test">Test</button> Scroll down to view JSON data<br>
<canvas id="compass" height=200 width=200></canvas>
<div id="status">Berlin, Germany</div>
JSON data source: <a href="http://api.wunderground.com" target="_blank">Weather Underground</a><br>
<textarea id="debug" spellcheck=false></textarea>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble utilizing a function with an async onload method within a service in Angular - why does the same function work flawlessly in a component?

I successfully created a component in Angular that can import an Excel file, convert it into an array, and display its content as a table on the page. The current implementation within the component looks like this: data-import.compoent.ts import { Compo ...

Determine the maximum size of a specified number of square divs that can fit within responsive parent divs

I am working on creating a grid of square divs inside a container with variable height and width. The number of square div's is predetermined. All square divs will have images with the same dimensions (similar to the example). They should align left ...

Dealing with multiple parameters within the app.param() function

Currently, I am developing an API using Express.js and facing a challenge in implementing an app.param() function for handling the id parameter in a GET request: app.param('id', (req, res, next, id) => { const envelopeIndex = Number(id); ...

Is it possible to determine if jQuery find returns true or false?

Snippet of HTML Code <div class="container1"> <div class="box1">Box 1</div> <div class="box2">Box 2</div> <div class="box3">Box 3</div> </div> <div clas ...

What is the process for activating a button after a checkbox has been selected? Additionally, how can a value be dynamically transferred from a checkbox to the rezBlock_1 block?

What could be the reason for my code not functioning properly? How can I enable a button once a checkbox is selected? Also, is there a way to dynamically move text from a checkbox to the rezBlock_1 block? CODPEN https://codepen.io/RJDio/pen/RwPgaaZ doc ...

Failed to convert video to blob and upload it due to readAsArrayBuffer returning an empty array

Currently, I am facing an issue while attempting to upload a video using Ionic, Capacitor, and React. To achieve this, I have integrated the cordova-video-capture-plus plugin into my project. The problem arises when I try to execute the readAsArrayBuffer ...

Utilizing the Array Object within a Callback Function

I am facing an issue with accessing data[i] in the callback function. Below is the code snippet: var data = ['Hello', 'World']; for(var i=0;i<data.length;i++){ console.log(data[i]); // This works perfectly // Using mysql to query ...

Get information from the server via an ajax callback without refreshing the page and dynamically refresh the current page content. Node.js and Express 4

I am trying to implement a form and an Ajax client script that sends the form data to Express. The code for the form looks like this: form#form-reflow(action='/', method='post', onsubmit="docreflow()") input#te ...

javascript utilizing key inputs

Is there a way I can create a function that activates when the "A" key on my keyboard is pressed, sending a signal to nupp('/TS'), and stops sending the signal when the "A" key is released? <html> <head> <script src=\"htt ...

AngularJS: accessing remote systems - a guide

I am looking to explain my objective clearly I need guidance on how to establish a remote desktop connection from my Angular.js application to a windows application running system. The server I am using is Google App Engine. My current ideas: The Windo ...

What exactly does the next() function do in NodeJS/SailsJS?

I recently came across a SailsJS tutorial where the next(); function was used for user authentication. However, I'm still unsure of its exact purpose. Can anyone provide clarification on this? ...

What could be causing the regular expression to fail in properly validating the website URL?

Here is the URL expression(regex) I am currently using to validate website URLs : /(https?:\/\/)(www)?[A-Za-z0-9.\-@_~]+\.[A-Za-z]{2,}(:[0-9]{2,5})?(\/[A-Za-z0-9\/_\-.~?&=]*)*/ My implementation of angular JS code l ...

Issues with Django Site Search Functionality

Currently working on a Django project, I have encountered an issue with the search bar on my localhost site. Despite adding the search bar, it fails to return any results when provided input. Upon inspecting the page source, I discovered some unfamiliar li ...

Switch up the Thumbnail Image based on the selected category

While testing a shopping site I created, I encountered an issue with changing the banners at the top of the page based on the category the user is viewing. This site is hosted on a server on my localhost, not using wordpress by the way. <div class=" ...

Guide to setting up Docker Nginx to work with an Express and React application on a Windows

After finding tutorials about CSS, React, and Node, I realized none of them combined all three. My goal is to learn how to deploy react websites on my domain for testing purposes. However, the learning process has been overwhelming with the cascade of new ...

What steps can I take to identify and manage a browser's inability to play a media file?

I am currently utilizing a JavaScript utility to stream mp3 content. Unfortunately, there are instances where I direct users to a file that cannot be played due to external factors. In such cases, Firebug displays an error message indicating that the file ...

Unable to showcase JavaScript outcome on the HTML page

I have been working on creating a JavaScript function to calculate the Highest Common Factor (HCF). While testing my code in the VS Code console, the correct value is displayed. However, I'm encountering an issue when trying to display the result on t ...

When a <a href> link is clicked, the Struts action should open as a popup

I have a form on my jsp page, <form action="test1_action" name="test" method="post" id="test"> Additionally, I have two distinct links: link1 and link2. When link1 is clicked, the form should be submitted with the action test1_action. $('#l ...

Maintain uniform height of divs while adjusting image size without altering padding

My challenge lies in creating a layout of images in columns with consistent padding between them. The ultimate goal is to ensure that the images align at the bottom, regardless of screen size variations as depicted in this image: The problem arises when t ...

`How can I dynamically alter the text color of a CSS class using code?`

Currently, I am incorporating Bootstrap.css into my project and utilizing the "form-control" class to style my aspx controls. However, I have encountered an issue where the font color of the textbox is appearing as grey when I desire it to be black. Unfo ...