Samples - Web Mapping Service (WMS)

Version 12


    ESRI JavaScript API code example

     

    The following is the ESRI Javascript example which displays the temperatures in Farhenheit on a ESRI light gray basemap.

     

    To launch this example, click on the following link: Javascript Example.

     

    <script type="text/javascript">
    var djConfig = {
    parseOnLoad : true
    };
    </script>
    <script type="text/javascript" src="http://serverapi.arcgisonline.com/jsapi/arcgis/?v=3.1"></script>
    <script type="text/javascript">
      dojo.require("dijit.dijit");
      dojo.require("dijit.layout.BorderContainer");
      dojo.require("dijit.layout.ContentPane");
      dojo.require("esri.map");
      var map, basemapGallery;
    
      function init() {
    
      //esri.config.defaults.io.alwaysUseProxy = true;
      //esri.config.defaults.io.proxyUrl = "http://localhost/proxy2/proxy.ashx";
    
      var initExtent = new esri.geometry.Extent({
          "xmin" : -15607937,
          "ymin" : 1303236,
          "xmax" : -6188752,
          "ymax" : 8468167,
          "spatialReference" : {
          "wkid" : 3857
          }
      });
    
      dojo.declare("my.WeatherTemperatureWMS", esri.layers.DynamicMapServiceLayer, {
          constructor : function() {
            this.initialExtent = this.fullExtent = initExtent;
            this.spatialReference = new esri.SpatialReference({
              wkid : 3857
            });
            this.loaded = true;
            this.onLoad(this);
          },
          getImageUrl : function(extent, width, height, callback) {
            var params = {
              SERVICE : "WMS",
              VERSION : "1.3.0",
              REQUEST : "GetMap",
              LAYERS : "TEMPERATURE_F_CURRENT",
              STYLES : "LOGO_BOTTOMLEFT",
              FORMAT : "image/png",
              BBOX : extent.ymin + "," + extent.xmin + "," + extent.ymax + "," + extent.xmax,
              CRS : "EPSG:" + extent.spatialReference.wkid,
              WIDTH : width,
              HEIGHT : height,
              TRANSPARENT : true
            }
            callback("http://weather-services.telventdtn.com/digest/wms_v1/wms.wsgi?" + dojo.objectToQuery(params));
          }
      });
    
      var wmsTemperatureLayer = new my.WeatherTemperatureWMS();
    
      map = new esri.Map("map", {
          extent : initExtent,
          wrapAround180 : true,
          slider : false
      });
    
      var basemap = new esri.layers.ArcGISTiledMapServiceLayer("http://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer");
      map.addLayer(basemap);
      map.addLayer(wmsTemperatureLayer);
    
      var referencemap = new esri.layers.ArcGISTiledMapServiceLayer("http://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Reference/MapServer");
      map.addLayer(referencemap);
    
      dojo.connect(map, 'onLoad', function(map) {
          //resize the map when the browser resizes
          dojo.connect(dijit.byId('map'), 'resize', map, map.resize);
      });
    
      var timerId = setInterval(timerMethod, 15000);
    
      function timerMethod() {
          var wmsExtent = esri.geometry.webMercatorToGeographic(map.extent);
          wmsTemperatureLayer.refresh();
      }
    
      //show map on load
      dojo.addOnLoad(init);
    </script>
              

     

    Back to top

    ESRI Flex API code example

     

    The following is the Flex API example which displays the temperatures in Fahrenheit on a ESRI light gray basemap.

     

    To launch this example, click on the following link: Flex Example.

     

    <?xml version="1.0" encoding="utf-8"?>
    <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
      xmlns:s="library://ns.adobe.com/flex/spark"
      xmlns:mx="library://ns.adobe.com/flex/mx"
      xmlns:esri="http://www.esri.com/2008/ags"
      pageTitle="FlexApplication1"
    >
    
    <esri:Map>
    
      <esri:extent>
          <esri:Extent xmin="-13041180" ymin="3837741" xmax="-5527114" ymax="6587028">
            <esri:SpatialReference wkid="3857"/>
          </esri:Extent>
      </esri:extent>
    
      <esri:ArcGISTiledMapServiceLayer url="http://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer" />
      <esri:ArcGISTiledMapServiceLayer url="http://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Reference/MapServer" />
    
      <esri:WMSLayer url="http://weather-services.telventdtn.com/basic/wms_v1/wms.wsgi" >
      <esri:visibleLayers>
          <s:ArrayList>
            <fx:String>TEMPERATURE_F_CURRENT</fx:String>
          </s:ArrayList>
      </esri:visibleLayers>
      </esri:WMSLayer>
    
    </esri:Map>
    
    </s:Application>
              

     

    Back to top

    ESRI SilverLight API code example

     

    The following is the SilverLight example which will place the current temperatures in Fahrenheit on a light gray basemap.

     

    <UserControl x:Class="SilverlightApplication2.MainPage"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      xmlns:esri="http://schemas.esri.com/arcgis/client/2009"
    >
    
    <Grid x:Name="LayoutRoot" Background="White">
    
    <esri:Map x:Name="MyMap" WrapAround="True">
    
      <esri:extent>
          <esri:Extent xmin="-13041180" ymin="3837741" xmax="-5527114" ymax="6587028">
            <esri:SpatialReference wkid="3857"/>
          </esri:Extent>
      </esri:extent>
    
    <esri:ArcGISTiledMapServiceLayer ID="MyLayer" Url="http://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer" />
    <esri:ArcGISTiledMapServiceLayer ID="MyLayer" Url="http://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Reference/MapServer" />
    
    <esri:WmsLayer ID="RadarWMSLayer"      
      Url="http://weather-services.telventdtn.com/basic/wms_v1/wms.wsgi"                    
      SkipGetCapabilities="False"      
      Layers="TEMPERATURE_F_CURRENT"
      Version="1.3.0"
      Opacity="1.0" />
    
    </esri:Map>
    
    </Grid>
    </UserControl>
              

     

    Back to top

    PROXY code example

     

    The following is an example for an authentication proxy in C#.

     

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace SilverlightApplication1.Web
    {
      public class Handler1 : IHttpHandler
      {
    
          public void ProcessRequest(HttpContext context)
          {
            string uri = context.Request.RawUrl.Substring(context.Request.RawUrl.IndexOf("?") + 1);
    
            System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(new Uri(uri));
            req.Method = context.Request.HttpMethod;
    
            // Set body of request for POST requests
            if (context.Request.InputStream.Length > 0) {
              byte[] bytes = new byte[context.Request.InputStream.Length];
              context.Request.InputStream.Read(bytes, 0, (int)context.Request.InputStream.Length);
              req.ContentLength = bytes.Length;
              req.ContentType = "application/x-www-form-urlencoded";
              System.IO.Stream outputStream = req.GetRequestStream();
              outputStream.Write(bytes, 0, bytes.Length);
              outputStream.Close();
            }
    
            if (true)
            {
              System.Net.NetworkCredential myCredentials = new System.Net.NetworkCredential("<>", "<>");
                //req.Credentials = myCredentials;
                System.Net.CredentialCache myCache = new System.Net.CredentialCache();
                myCache.Add(req.RequestUri, "Digest", myCredentials);
                req.UseDefaultCredentials = false;
                req.PreAuthenticate = true;
                req.Credentials = myCache.GetCredential(new Uri(uri), "Digest");
                req.UserAgent = "MSIE"; // tell Apache that the Authentication violates RFC for Diget
              }
              System.Net.WebResponse res = null;
              try {
                res = req.GetResponse();
              }
              catch (System.Net.WebException we) {
                System.Net.HttpWebResponse hwe = (System.Net.HttpWebResponse)we.Response;
                return;
              }
              catch (System.IO.IOException ioe) {
                return;
              }
              catch (System.Exception se) {
                return;
              }
    
              context.Response.ContentType = res.ContentType;
    
              // Text responses
              if (res.ContentType.Contains("text") || res.ContentType.Contains("application/vnd.ogc")) {
                System.IO.StreamReader sr = new System.IO.StreamReader(res.GetResponseStream());
                string strResponse = sr.ReadToEnd();
                context.Response.Write(strResponse);
              }
              // Convert all png images to 32-bit for full alpha (transparency support) in Silverlight
              else if (res.ContentType.Contains("/png")) {
                System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(res.GetResponseStream());
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                context.Response.BinaryWrite(ms.ToArray());
              }
              else if (res.ContentType.Contains("/gif")) {
                System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(res.GetResponseStream());
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
                context.Response.BinaryWrite(ms.ToArray());
              }
              else
              {
                // Binary responses (non-png images)
                byte[] b;
                using (System.IO.BinaryReader br = new System.IO.BinaryReader(res.GetResponseStream())) {
                  b = br.ReadBytes(500000);
                  br.Close();
                }
                context.Response.BinaryWrite(b);
              }
              context.Response.End();
            }
    
            public bool IsReusable { get { return false; } }
        }
      }
              

     

    Back to top

     

    Google JavaScript API code example

     

    The following is the Google Javascript example which displays the temperatures in Fahrenheit on a basemap.

     

    You will need to obtain your Google Maps API Key from https://developers.google.com/maps/documentation/javascript/tutorial.

     

    <!DOCTYPE html>
    <html>
      <head>
          <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
          <style type="text/css">
            html { height: 100% }
            body { height: 100%; margin: 0; padding: 0 }
              #map-canvas { width: 1000px; height: 650px;}
          </style>
          <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=<Your Key Goes Here>&sensor=false&libraries=weather">
          </script>
          <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js">
          </script>
          <script type="text/javascript">
            var map = null;
            function initialize() {
              var mapOptions = {
                center: new google.maps.LatLng(40.716216, -90.213393),
                zoom: 6,
                mapTypeId: google.maps.MapTypeId.ROADMAP
              };
              map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
              console.log('hello' );
              var imageBounds = new google.maps.LatLngBounds(
                      new google.maps.LatLng(40.716216, -74.213393),
                      new google.maps.LatLng(40.765641, -74.139235));
    
              google.maps.event.addListener(map, 'dragend', getLayer);
              google.maps.event.addListener(map, 'zoom_changed', getLayer);
    
              // Create the DIV to hold the control and
              // call the HomeControl() constructor passing
              // in this DIV.
              var featureInfoControlDiv = document.createElement('div');
              var featureInfoControl = new FeatureInfoControl(featureInfoControlDiv, map);
    
              featureInfoControlDiv.index = 1;
              map.controls[google.maps.ControlPosition.TOP_RIGHT].push(featureInfoControlDiv);
    
              var legendControlDiv = document.createElement('div');
              var legendControl = new LegendControl(legendControlDiv, map);
    
              legendControlDiv.index = 1;
              map.controls[google.maps.ControlPosition.RIGHT_CENTER].push(legendControlDiv);
    
              window.setTimeout(getLayer, 3000);
    
        }
    
        google.maps.event.addDomListener(window, 'load', initialize);
    
        var oldmap = null;
        var imageBounds = null;
    
        function getLayer() {
    
            imageBounds = map.getBounds();
    
            var ll = imageBounds.getSouthWest();
            var ur = imageBounds.getNorthEast();
            var LL = WGS84toGoogleBing(ll);
            var UR = WGS84toGoogleBing(ur);
    
            var bbox = ll.lng() + "," + ll.lat() + "," + ur.lng() + "," + ur.lat();
    
            var div = map.getDiv();
    
            //base WMS URL
            var url = "https://weather-services.telventdtn.com/basic/wms_v1/wms.wsgi?";
            url += "REQUEST=GetMap"; //WMS operation
            url += "&SERVICE=WMS";    //WMS service
            url += "&VERSION=1.1.1";  //WMS version
            url += "&LAYERS=" + "RADAR_US_CURRENT"; //WMS layers
            url += "&STYLES=" + ""; //WMS layers
            url += "&FORMAT=image/png"; //WMS format
            url += "&BGCOLOR=0xFFFFFF";
            url += "&TRANSPARENT=TRUE";
            url += "&SRS=EPSG:4326";    //set WGS84
            url += "&BBOX=" + bbox;      // set bounding box
            url += "&WIDTH=" + div.clientWidth;
            url += "&HEIGHT=" + div.clientHeight;
    
            if (oldmap!=null)
              oldmap.setMap(null);
    
            xmlHttp = new XMLHttpRequest();
            xmlHttp.onreadystatechange = reportStatus;
    
            try {
              xmlHttp.open("GET", url, true);
              xmlHttp.setRequestHeader("Authorization", " Basic " + encodePlain('<Your WMS Username Goes Here>:<Your WMS Password Goes Here>'));
              xmlHttp.responseType = "arraybuffer";
              xmlHttp.send(null);
            } catch (e) {
              alert(e);
            }
        }
    
        var xmlHttp = null;
    
        function reportStatus() {
            if (xmlHttp.readyState == 4) {
              if (xmlHttp.status == 200) {
                var byteArray = new Uint8Array(xmlHttp.response);
                var image = 'data:image/png;base64,' + base64ArrayBuffer(byteArray);
                oldmap = new google.maps.GroundOverlay( image, imageBounds, { clickable: true });
                oldmap.setMap(map);
              }
            }
        }
    
        function WGS84toGoogleBing(l) {
          var x = l.lng() * 20037508.34 / 180.0;
          var y = Math.log(Math.tan((90.0 + l.lat()) * Math.PI / 360.0)) / (Math.PI / 180.0);
          y = y * 20037508.34 / 180.0;
          return new google.maps.Point(x, y);
        }
    
        function GoogleBingtoWGS84Mercator(p) {
          var lon = (p.x / 20037508.34) * 180.0;
          var lat = (p.y / 20037508.34) * 180.0;
          lat = 180.0 / Math.PI * (2.0 * Math.atan(Math.exp(lat * Math.PI / 180.0)) - Math.PI / 2.0);
          return new google.maps.LatLng (lat, lon);
        }
    
        function getInfo(eventArg) {
    
          var imageBounds = map.getBounds();
          var el = document.getElementById('getInfo');
          var text = el.options[el.selectedIndex].text;
    
          if (!imageBounds.isEmpty() && text!='None') {
            var p = eventArg.latLng;
            var div = map.getDiv();
    
            var ll = imageBounds.getSouthWest();
            var ur = imageBounds.getNorthEast();
    
            var x = div.clientWidth  * (p.lng() - ll.lng()) / (ur.lng() - ll.lng());
            var y = div.clientHeight * (1.0 - (p.lat() - ll.lat()) / (ur.lat() - ll.lat()));
    
            var LL = WGS84toGoogleBing(ll);
            var UR = WGS84toGoogleBing(ur);
    
            var url = "https://weather-services.telventdtn.com/basic/wms_v1/wms.wsgi?";
            url += "REQUEST=GetFeatureInfo"; //WMS operation
            url += "&SERVICE=WMS";    //WMS service
            url += "&VERSION=1.1.1";  //WMS version
            url += "&LAYERS=" + "USRA.SMOOTH,CNRA"; //WMS layers
            url += "&STYLES=" + ","; //WMS layers
            url += "&FORMAT=image/png"; //WMS format
            url += "&BGCOLOR=0xFFFFFF";
            url += "&TRANSPARENT=TRUE";
            url += "&SRS=EPSG:4326";    //set WGS84
            url += "&BBOX=" + bbox;      // set bounding box
            url += "&WIDTH=" + div.clientWidth;
            url += "&HEIGHT=" + div.clientHeight;
            url += "&QUERY_LAYERS=" + "USRA.SMOOTH";
            url += "&X=" + x;
            url += "&Y=" + y;
    
            if (text == 'XML')
                url += "&INFO_FORMAT=text/xml";
            else
                url += "&INFO_FORMAT=text/html";
    
            window.open(url);
          }
        }
    
        /**
        * The FeatureInfoControl adds a control to the map that simply
        * returns the user to Chicago. This constructor takes
        * the control DIV as an argument.
        * @constructor
        */
        function FeatureInfoControl(controlDiv, map) {
    
          // Set CSS styles for the DIV containing the control
          // Setting padding to 5 px will offset the control
          // from the edge of the map
          controlDiv.style.padding = '5px';
    
          // Set CSS for the control border
          var controlUI = document.createElement('div');
          controlUI.style.backgroundColor = 'white';
          controlUI.style.borderStyle = 'solid';
          controlUI.style.borderWidth = '2px';
          controlUI.style.cursor = 'pointer';
          controlUI.style.textAlign = 'center';
          controlUI.title = 'Select GetFeatureInfo Format';
          controlDiv.appendChild(controlUI);
    
          // Set CSS for the control interior
          var controlText = document.createElement('div');
          controlText.style.fontFamily = 'Arial,sans-serif';
          controlText.style.fontSize = '12px';
          controlText.style.paddingLeft = '4px';
          controlText.style.paddingRight = '4px';
          controlText.innerHTML = '<b>Info Type: </b><select id="getInfo" name="getInfo"><option value="none">None</option>  <option value="html">HTML</option>  <option value="xml">XML</option></select>';
          controlUI.appendChild(controlText);
        }
    
        /**
        * The LegendControl adds a control to the map that simply
        * returns the user to Chicago. This constructor takes
        * the control DIV as an argument.
        * @constructor
        */
        function LegendControl(controlDiv, map) {
    
          // Set CSS styles for the DIV containing the control
          // Setting padding to 5 px will offset the control
          // from the edge of the map
          controlDiv.style.padding = '5px';
    
          // Set CSS for the control border
          var controlUI = document.createElement('div');
          controlUI.style.backgroundColor = 'white';
          controlUI.style.borderStyle = 'solid';
          controlUI.style.borderWidth = '2px';
          controlUI.style.cursor = 'pointer';
          controlUI.style.textAlign = 'center';
          controlUI.title = 'Legends';
          controlDiv.appendChild(controlUI);
    
          // Set CSS for the control interior
          var controlText = document.createElement('div');
          controlText.style.fontFamily = 'Arial,sans-serif';
          controlText.style.fontSize = '12px';
          controlText.style.paddingLeft = '4px';
          controlText.style.paddingRight = '4px';
          controlText.innerHTML = '<a href="http://wx-bld-bvldev01/legends/Precipitation.png"><b>Precipitation</b></a>';
          controlUI.appendChild(controlText);
    
        }
    
        var b64array = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    
        function encodePlain(input) {
          var base64 = "";
          var hex = "";
          var chr1, chr2, chr3 = "";
          var enc1, enc2, enc3, enc4 = "";
          var i = 0;
    
          do {
            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);
    
            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;
    
            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }
    
            base64  = base64  +
            b64array.charAt(enc1) +
            b64array.charAt(enc2) +
            b64array.charAt(enc3) +
            b64array.charAt(enc4);
            chr1 = chr2 = chr3 = "";
            enc1 = enc2 = enc3 = enc4 = "";
          } while (i < input.length);
    
          return base64;
        }
    
        function base64ArrayBuffer(arrayBuffer) {
          var base64 = ''
          var encodings = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
    
          var bytes = new Uint8Array(arrayBuffer)
          var byteLength = bytes.byteLength
          var byteRemainder = byteLength % 3
          var mainLength = byteLength - byteRemainder
    
          var a, b, c, d
          var chunk
    
          // Main loop deals with bytes in chunks of 3
          for (var i = 0; i < mainLength; i = i + 3) {
    
            // Combine the three bytes into a single integer
            chunk = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2]
    
            // Use bitmasks to extract 6-bit segments from the triplet
            a = (chunk & 16515072) >> 18 // 16515072 = (2^6 - 1) << 18
            b = (chunk & 258048) >> 12 // 258048  = (2^6 - 1) << 12
            c = (chunk & 4032) >> 6 // 4032    = (2^6 - 1) << 6
            d = chunk & 63              // 63      = 2^6 - 1
    
            // Convert the raw binary segments to the appropriate ASCII encoding
            base64 += encodings[a] + encodings[b] + encodings[c] + encodings[d]
          }
    
          // Deal with the remaining bytes and padding
          if (byteRemainder == 1) {
            chunk = bytes[mainLength]
    
            a = (chunk & 252) >> 2 // 252 = (2^6 - 1) << 2
    
            // Set the 4 least significant bits to zero
            b = (chunk & 3) << 4 // 3  = 2^2 - 1
    
            base64 += encodings[a] + encodings[b] + '=='
          } else if (byteRemainder == 2) {
            chunk = (bytes[mainLength] << 8) | bytes[mainLength + 1]
    
            a = (chunk & 64512) >> 10 // 64512 = (2^6 - 1) << 10
            b = (chunk & 1008) >> 4 // 1008  = (2^6 - 1) << 4
    
            // Set the 2 least significant bits to zero
            c = (chunk & 15) << 2 // 15    = 2^4 - 1
    
            base64 += encodings[a] + encodings[b] + encodings[c] + '='
          }
    
          return base64
        }
    
      </script>
      </head>
      <body>
          <div id="map-canvas"/>
      </body>
    </html>
              

     

    Back to top

     

    Bing JavaScript API code example

     

    The following is the Bing Javascript example that displays the radar on a basemap. It uses OAuth for authentication which you can interactively use with oauth_example_wms.html.

     

    You will need to create a Bing maps account and key using https://www.bingmapsportal.com/.

    For the Bing OAuth example you will need to download and use oauth.js and sha1.js.

     

    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
      <head>
      <title></title>
      <script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>
      <script type="text/javascript" src="oauth.js"></script>
      <script type="text/javascript" src="sha1.js"></script>
      <script type="text/javascript">
      var map = null;
    
      function GetMap() {
        map = new Microsoft.Maps.Map(document.getElementById("mapDiv"), { credentials: <your Bing key here>, center: new Microsoft.Maps.Location(48.03, -80.4), zoom: 5, mapTypeId: Microsoft.Maps.MapTypeId.road });
        try {
          Microsoft.Maps.Events.addHandler(map, 'viewchangeend', onViewChangeEnd );
        }catch (err) {
          alert('Error Message:' + err.message);
        }
      }
    
      function WGS84toGoogleBing(p) {
        var x = p.longitude * 20037508.34 / 180.0;
        var y = Math.log(Math.tan((90.0 + p.latitude) * Math.PI / 360.0)) / (Math.PI / 180.0);
        y = y * 20037508.34 / 180.0;
        return new Microsoft.Maps.Point(x, y);
      }
    
      function getImage(e) {
        var center = map.getCenter();
        bounds = map.getBounds();
        uriWidth = map.getWidth();
        uriHeight = map.getHeight();
        var l = bounds.center.longitude - bounds.width / 2.0;
        var r = bounds.center.longitude + bounds.width / 2.0;
    
        try {
        var LL = new Microsoft.Maps.Location(bounds.getSouth(), bounds.getWest());
        var UR = new Microsoft.Maps.Location(bounds.getNorth(), bounds.getEast());
        var ll = WGS84toGoogleBing(LL);
        var ur = WGS84toGoogleBing(UR);
        var bbox = ll.x + "," + ll.y + "," + ur.x + "," + ur.y;
    
        var uri = "http://weather-services.telventdtn.com/basic/wms_v1/wms.wsgi?service=WMS&version=1.3.0&request=GetMap&layers=RADAR_US_CURRENT&"
                  + bbox + "&width=" + uriWidth + "&height=" + uriHeight + "&STYLES=&format=image/png&CRS=EPSG:3857&TRANSPARENT=TRUE";
    
        var d = new Date();
        var consumerSecret = "your_web_services_username";
        var oauth_consumer_key = "your_web_services_password";
        var method = "GET";
        var methodName = "HMAC-SHA1";
        var action = "http://weather-services.telventdtn.com/oauth/wms_v1/wms.wsgi";
        var parameters = {
                  service: "WMS",
                  version: "1.3.0",
                  request: "GetMap",
                  layers: "RADAR_US_CURRENT",
                  bbox: bbox,
                  width: uriWidth,
                  height: uriHeight,
                  STYLES: "",
                  format: "image/png",
                  CRS: "EPSG:3857",
                  TRANSPARENT: "TRUE",
                  oauth_version: "1.0",
                  oauth_consumer_key: oauth_consumer_key,
                  oauth_timestamp: d.getTime()/1000,
                  oauth_nonce: OAuth.nonce(16),
                  oauth_signature_method: "HMAC-SHA1"
                };
    
        var baseString = OAuth.SignatureMethod.getBaseString({ method: method, action: action, parameters: parameters });
        var signer = OAuth.SignatureMethod.newMethod(methodName, { consumerSecret: consumerSecret, tokenSecret: "" });
        var sign = signer.getSignature(baseString);  
        var p0 = OAuth.SignatureMethod.normalizeParameters(parameters);
    
        uri = OAuth.SignatureMethod.normalizeUrl(action) + "?" + p0 + "&oauth_signature=" + sign;
    
        xmlHttp = new XMLHttpRequest();
        xmlHttp.onreadystatechange = reportStatus;
    
        try {
          xmlHttp.open("GET", uri, true );
          xmlHttp.responseType = "arraybuffer";
          xmlHttp.send(null);
        } catch (e) {
          alert(e);
        }
    
        }
        catch (err) {
          alert('Error Message:' + err.message);
        }
      }
    
      var xmlHttp = null;
      var bounds = null;
      var uriWidth = null;
      var uriHeight = null;
    
      function reportStatus() {
    
        if (xmlHttp.readyState == 4) {
    
        if (xmlHttp.status == 200) {
          var byteArray = new Uint8Array(xmlHttp.response);
          var image = 'data:image/png;base64,' + base64ArrayBuffer(byteArray);
          var position = new Microsoft.Maps.Location(bounds.getSouth(), bounds.getWest() + bounds.width / 2.0);
          var pushpinOptions = { icon: image, width: uriWidth, height: uriHeight };
          var pushpin = new Microsoft.Maps.Pushpin(position, pushpinOptions);
          map.entities.clear();
          map.entities.push(pushpin);
        }
        }
      }
    
      var b64array = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    
      function encodePlain(input) {
        var base64 = "";
        var hex = "";
        var chr1, chr2, chr3 = "";
        var enc1, enc2, enc3, enc4 = "";
        var i = 0;
    
        do {
        chr1 = input.charCodeAt(i++);
        chr2 = input.charCodeAt(i++);
        chr3 = input.charCodeAt(i++);
    
        enc1 = chr1 >> 2;
        enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
        enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
        enc4 = chr3 & 63;
    
        if (isNaN(chr2)) {
          enc3 = enc4 = 64;
        } else if (isNaN(chr3)) {
          enc4 = 64;
        }
    
        base64 = base64 +
        b64array.charAt(enc1) +
        b64array.charAt(enc2) +
        b64array.charAt(enc3) +
        b64array.charAt(enc4);
        chr1 = chr2 = chr3 = "";
        enc1 = enc2 = enc3 = enc4 = "";
        } while (i < input.length);
    
        return base64;
      }
    
      function base64ArrayBuffer(arrayBuffer) {
        var base64 = ''
        var encodings = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
    
        var bytes = new Uint8Array(arrayBuffer)
        var byteLength = bytes.byteLength
        var byteRemainder = byteLength % 3
        var mainLength = byteLength - byteRemainder
    
        var a, b, c, d
        var chunk
    
        // Main loop deals with bytes in chunks of 3
        for (var i = 0; i < mainLength; i = i + 3) {
    
        // Combine the three bytes into a single integer
        chunk = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2]
    
        // Use bitmasks to extract 6-bit segments from the triplet
        a = (chunk & 16515072) >> 18 // 16515072 = (2^6 - 1) << 18
        b = (chunk & 258048) >> 12 // 258048  = (2^6 - 1) << 12
        c = (chunk & 4032) >> 6 // 4032    = (2^6 - 1) << 6
        d = chunk & 63              // 63      = 2^6 - 1
    
        // Convert the raw binary segments to the appropriate ASCII encoding
        base64 += encodings[a] + encodings[b] + encodings[c] + encodings[d]
        }
    
      // Deal with the remaining bytes and padding
      if (byteRemainder == 1) {
        chunk = bytes[mainLength]
        a = (chunk & 252) >> 2 // 252 = (2^6 - 1) << 2
    
        // Set the 4 least significant bits to zero
        b = (chunk & 3) << 4 // 3  = 2^2 - 1
    
        base64 += encodings[a] + encodings[b] + '=='
      } else if (byteRemainder == 2) {
        chunk = (bytes[mainLength] << 8) | bytes[mainLength + 1]
        a = (chunk & 64512) >> 10 // 64512 = (2^6 - 1) << 10
        b = (chunk & 1008) >> 4 // 1008  = (2^6 - 1) << 4
    
        // Set the 2 least significant bits to zero
        c = (chunk & 15) << 2 // 15    = 2^4 - 1
    
        base64 += encodings[a] + encodings[b] + encodings[c] + '='
      }
    
      return base64
    }
    
    function onViewChangeEnd(e) {
      getImage(e);
    }
      </script>
      </head>
      <body onload="GetMap();">
    <div id='mapDiv' style="position:absolute; top:0px; left:0; width:100%; height:100%;"></div>
    </body>
    </html>
              

    Back to top

     

    Bing JavaScript API Radar Animation code example

     

    The following is the Bing Javascript example that animates the radar on a basemap. It uses OAuth for authentication which you can interactively use with oauth_example_wms.html.

     

    You will need to create a Bing maps account and key using https://www.bingmapsportal.com/

    For the Bing OAuth example you will need to download and use oauth.js and sha1.js.

     

    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
      <title></title>
      <script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>
      <script type="text/javascript" src="oauth.js"></script>
      <script type="text/javascript" src="sha1.js"></script>
      <script type="text/javascript">
        var map = null;
        function GetMap() {
          map = new Microsoft.Maps.Map(document.getElementById("mapDiv"), { credentials: <your Bing key here>, center: new Microsoft.Maps.Location(38.03, -88.4), zoom: 5, mapTypeId: Microsoft.Maps.MapTypeId.road });
          try {
            Microsoft.Maps.Events.addHandler(map, 'viewchangeend', onViewChangeEnd);
          }
          catch (err) {
            alert('Error Message:' + err.message);
          }
        }
        function WGS84toGoogleBing(p) {
          var x = p.longitude * 20037508.34 / 180.0;
          var y = Math.log(Math.tan((90.0 + p.latitude) * Math.PI / 360.0)) / (Math.PI / 180.0);
          y = y * 20037508.34 / 180.0;
          return new Microsoft.Maps.Point(x, y);
        }
        function getImage(e) {
          if (playTimer != null) {
            clearInterval(playTimer);
            playTimer = null;
            playing = 0;
            document.getElementById("Button1").value = "Play";
            clearFrames();
            }
          var center = map.getCenter();
          bounds = map.getBounds();
          uriWidth = map.getWidth();
          uriHeight = map.getHeight();
          var l = bounds.center.longitude - bounds.width / 2.0;
          var r = bounds.center.longitude + bounds.width / 2.0;
          try {
            var LL = new Microsoft.Maps.Location(bounds.getSouth(), bounds.getWest());
            var UR = new Microsoft.Maps.Location(bounds.getNorth(), bounds.getEast());
            if (LL.longitude > UR.longitude) {
              if (UR.longitude < 0.0 && (LL.longitude - 360.0) < 0.0) LL.longitude -= 360.0;
              else if (LL.longitude > 0.0 && (UR.longitude + 360.0) > 0.0) UR.longitude += 360.0;
            }
            var ll = WGS84toGoogleBing(LL);
            var ur = WGS84toGoogleBing(UR);
            var bbox = ll.x + "," + ll.y + "," + ur.x + "," + ur.y;
            var d = new Date();
            var consumerSecret = "your_web_services_username";
            var oauth_consumer_key = "your_web_services_password";
            var method = "GET";
            var methodName = "HMAC-SHA1";
            var action = "http://weather-services.telventdtn.com/oauth/wms_v1/wms.wsgi";
            var parameters = {
              service: "WMS", version: "1.3.0", request: "GetMap", layers: "RADAR_US_CURRENT", bbox: bbox, width: uriWidth, height: uriHeight, STYLES: "", format: "image/png", CRS: "EPSG:3857", TRANSPARENT: "TRUE",
              oauth_version: "1.0", oauth_consumer_key: oauth_consumer_key, oauth_timestamp: d.getTime() / 1000, oauth_nonce: OAuth.nonce(16),
              oauth_signature_method: "HMAC-SHA1"
            };
            var baseString = OAuth.SignatureMethod.getBaseString({ method: method, action: action, parameters: parameters });
            //console.log("baseString = " + baseString);
            var signer = OAuth.SignatureMethod.newMethod(methodName, { consumerSecret: consumerSecret, tokenSecret: "" });
            var sign = signer.getSignature(baseString);
            //console.log("Signature = " + sign);
            //console.log("normalizeUrl = " + OAuth.SignatureMethod.normalizeUrl(action));
            //console.log("normalizeParameters = " + OAuth.SignatureMethod.normalizeParameters(parameters));
            uri = OAuth.SignatureMethod.normalizeUrl(action) + "?" + OAuth.SignatureMethod.normalizeParameters(parameters) + "&oauth_signature=" + sign;
            console.log(uri);
            xmlHttp = new XMLHttpRequest();
            xmlHttp.onreadystatechange = reportStatus;
    
            try {
              xmlHttp.open("GET", uri, true);
              xmlHttp.responseType = "arraybuffer";
              xmlHttp.send(null);
            } catch (e) {
              alert(e);
            }
          }
          catch (err) {
            alert('Error Message:' + err.message);
          }
        }
        var xmlHttp = null;
        var bounds = null;
        var uriWidth = null;
        var uriHeight = null;
        function reportStatus() {
          if (xmlHttp.readyState == 4) {
            if (xmlHttp.status == 200) {
              var byteArray = new Uint8Array(xmlHttp.response);
              var image = 'data:image/png;base64,' + base64ArrayBuffer(byteArray);
              var position = new Microsoft.Maps.Location(bounds.getSouth(), bounds.getWest() + bounds.width / 2.0);
              var pushpinOptions = { icon: image, width: uriWidth, height: uriHeight };
              var pushpin = new Microsoft.Maps.Pushpin(position, pushpinOptions);
              map.entities.clear();
              map.entities.push(pushpin);
            }
          }
        }
        var maxFrames = 16;
        var Frames = new Array(maxFrames);
        var xmlHttpList = new Array(maxFrames);
        function getImages() {
          if (playTimer != null) {
            clearInterval(playTimer);
            playTimer = null;
            playing = 0;
            document.getElementById("Button1").value = "Play";
            clearFrames();
          }
          var date = new Date();
          var utc = date.getTime();
          var t = 300000 * Math.floor(utc / 300000);
          for (var i = maxFrames-1; i >= 0; i--) {
            date = new Date(t - i*300000);
            getSingleImage(date.toISOString().slice(0, 19), maxFrames - i - 1);
          }
          currentFrame = 0;
          playTimer = setInterval(nextFrame, 150);
        }
        var currentFrame = 0;
        var playTimer = null;
        function nextFrame() {
          //console.log(currentFrame);
          if (Frames[currentFrame] != null) {
            console.log('.');
            map.entities.clear();
            map.entities.push(Frames[currentFrame]);
            }
          currentFrame++;
          if (currentFrame > maxFrames) currentFrame = 0;
        }
        function clearFrames() {
          for (var i = 0; i < maxFrames; i++) {
            Frames[i] = null;
          }
        }
        var playing = 0;
        function play_pause() {
          if (playing) {
            clearInterval(playTimer);
            playTimer = null;
            playing = 0;
            clearFrames();
            getImage(null);
            console.log("stop");
            document.getElementById("Button1").value = "Play";
          } else {
            clearInterval(playTimer);
            timer = null;
            getImages();
            playing = 1;
            console.log("start");
            playTimer = setInterval(nextFrame, 100);
            document.getElementById("Button1").value = "Pause";
          }
        }
        function getSingleImage(e,i) {
          var center = map.getCenter();
          bounds = map.getBounds();
          uriWidth = map.getWidth();
          uriHeight = map.getHeight();
          var l = bounds.center.longitude - bounds.width / 2.0;
          var r = bounds.center.longitude + bounds.width / 2.0;
          try {
            var LL = new Microsoft.Maps.Location(bounds.getSouth(), bounds.getWest());
            var UR = new Microsoft.Maps.Location(bounds.getNorth(), bounds.getEast());
            if (LL.longitude > UR.longitude) {
              if (UR.longitude < 0.0 && (LL.longitude - 360.0) < 0.0) LL.longitude -= 360.0;
              else if (LL.longitude > 0.0 && (UR.longitude + 360.0) > 0.0) UR.longitude += 360.0;
            }
            var ll = WGS84toGoogleBing(LL);
            var ur = WGS84toGoogleBing(UR);
            var bbox = ll.x + "," + ll.y + "," + ur.x + "," + ur.y;
            var d = new Date();
            var consumerSecret = "your_web_services_username";
            var oauth_consumer_key = "your_web_services_password";
            var method = "GET";
            var methodName = "HMAC-SHA1";
            var action = "http://weather-services.telventdtn.com/oauth/wms_v1/wms.wsgi";
            var parameters = {
              service: "WMS", version: "1.3.0", request: "GetMap", layers: "RADAR_US_CURRENT", bbox: bbox, width: uriWidth, height: uriHeight, STYLES: "", format: "image/png", CRS: "EPSG:3857", TRANSPARENT: "TRUE",
              oauth_version: "1.0", oauth_consumer_key: oauth_consumer_key, oauth_timestamp: d.getTime() / 1000, oauth_nonce: OAuth.nonce(16),
              oauth_signature_method: "HMAC-SHA1", TIME: e
            };
            var baseString = OAuth.SignatureMethod.getBaseString({ method: method, action: action, parameters: parameters });
            //console.log("baseString = " + baseString);
            var signer = OAuth.SignatureMethod.newMethod(methodName, { consumerSecret: consumerSecret, tokenSecret: "" });
            var sign = signer.getSignature(baseString);
            uri = OAuth.SignatureMethod.normalizeUrl(action) + "?" + OAuth.SignatureMethod.normalizeParameters(parameters) + "&oauth_signature=" + sign;
            //console.log(uri);
    
            xmlHttpList[i] = new XMLHttpRequest();
            xmlHttpList[i].onreadystatechange = function () {
              console.log(xmlHttpList[i].status);
              if (xmlHttpList[i].status == 200) {
                try {
                  var byteArray = new Uint8Array(xmlHttpList[i].response);
                  var image = 'data:image/png;base64,' + base64ArrayBuffer(byteArray);
                  var position = new Microsoft.Maps.Location(bounds.getSouth(), bounds.getWest() + bounds.width / 2.0);
                  var pushpinOptions = { icon: image, width: uriWidth, height: uriHeight };
                  Frames[i] = new Microsoft.Maps.Pushpin(position, pushpinOptions);
                } catch (e) {
                  console.log(e.message)
                  //alert(e);
                }
              }
            };
            try {
              xmlHttpList[i].open("GET", uri, true);
              xmlHttpList[i].responseType = "arraybuffer";
              xmlHttpList[i].send(null);
            } catch (e) {
              console.log(e.message)
              //alert(e);
            }
          }
          catch (err) {
            alert('Error Message:' + err.message);
          }
          return null;
        }
    
        var b64array = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    
        function encodePlain(input) {
          var base64 = "";
          var hex = "";
          var chr1, chr2, chr3 = "";
          var enc1, enc2, enc3, enc4 = "";
          var i = 0;
    
          do {
            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);
            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;
    
            if (isNaN(chr2)) {
              enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
              enc4 = 64;
            }
    
            base64 = base64 +
              b64array.charAt(enc1) +
              b64array.charAt(enc2) +
              b64array.charAt(enc3) +
              b64array.charAt(enc4);
            chr1 = chr2 = chr3 = "";
            enc1 = enc2 = enc3 = enc4 = "";
          } while (i < input.length);
    
          return base64;
        }
    
        function base64ArrayBuffer(arrayBuffer) {
          var base64 = ''
          var encodings = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
          var bytes = new Uint8Array(arrayBuffer)
          var byteLength = bytes.byteLength
          var byteRemainder = byteLength % 3
          var mainLength = byteLength - byteRemainder
          var a, b, c, d
          var chunk
    
          // Main loop deals with bytes in chunks of 3
          for (var i = 0; i < mainLength; i = i + 3) {
            // Combine the three bytes into a single integer
            chunk = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2]
    
            // Use bitmasks to extract 6-bit segments from the triplet
            a = (chunk & 16515072) >> 18 // 16515072 = (2^6 - 1) << 18
            b = (chunk & 258048) >> 12 // 258048  = (2^6 - 1) << 12
            c = (chunk & 4032) >> 6 // 4032    = (2^6 - 1) << 6
            d = chunk & 63              // 63      = 2^6 - 1
    
            // Convert the raw binary segments to the appropriate ASCII encoding
            base64 += encodings[a] + encodings[b] + encodings[c] + encodings[d]
          }
    
          // Deal with the remaining bytes and padding
          if (byteRemainder == 1) {
            chunk = bytes[mainLength]
            a = (chunk & 252) >> 2 // 252 = (2^6 - 1) << 2
    
            // Set the 4 least significant bits to zero
            b = (chunk & 3) << 4 // 3  = 2^2 - 1
            base64 += encodings[a] + encodings[b] + '=='
          } else if (byteRemainder == 2) {
            chunk = (bytes[mainLength] << 8) | bytes[mainLength + 1]
            a = (chunk & 64512) >> 10 // 64512 = (2^6 - 1) << 10
            b = (chunk & 1008) >> 4 // 1008  = (2^6 - 1) << 4
    
            // Set the 2 least significant bits to zero
            c = (chunk & 15) << 2 // 15    = 2^4 - 1
            base64 += encodings[a] + encodings[b] + encodings[c] + '='
          }
          return base64
        }
    
        function onViewChangeEnd(e) {
          getImage(e);
        }
      </script>
    </head>
    <body onload="GetMap();">
      <input id="Button1" style="top:0px;" type="button" value="Play" onclick="play_pause()" />
      <div id='mapDiv' style="position:absolute; top:40px; left:0; width:100%; height:95%;"></div>
    </body>
    </html>
              

    Back to top

     

    Request a trial

     

    Click to request your trial of WeatherSentry Web Services.