Using KML, KMZ, PushPins, and more with Bing Maps

By Alan S. at August 26, 2010 02:17
Filed Under: Training, Web / Software Development

imageAn Example-Driven, Beginner's Guide to Building Interactive Maps with Bing, Yahoo!, and Google Maps is finally here!

 

Map Scripting 101: An Example-Driven Guide to Building Interactive Maps with Bing, Yahoo!, and Google Maps (No Starch Press, Aug 2010, 376 pp, $34.95, ISBN 9781593272715) is an example-based beginner's guide to map scripting. Author Adam DuVander delivers a cookbook of 73 immediately useful mapping scripts like a local concert tracker, a Twitter friend-finder, and a real-time weather map. And because the book is based on the cross-platform Mapstraction JavaScript library, readers can use virtually any mapping service, including OpenStreetMap, MapQuest, Google Maps, Yahoo!, and Bing.

 

In this book, you’ll learn to:

checkmark_red Create, embed, and manipulate basic maps by setting zoom levels and map boundaries

checkmark_red Show, hide, and filter location markers and info-bubbles

checkmark_red Customize maps for visitors based on their location

checkmark_red Use common data formats like Google Earth's KML, GeoRSS, and GPS XML (GPX)

checkmark_red Create graphical overlays on maps to better analyze data and trends

checkmark_red Use freely available geodata from websites like Yelp and Upcoming—and public domain geodata from the US government

 

We do a lot of work with Bing Maps and this book is already getting worn from use. The step by step guide and the library reference is incredibly helpful and drastically cuts our development time. If you work with Google Maps or Bing Maps then this script reference is something that should be open and on your desk!

Bookmark and Share DotnetKicks dotnetshoutout

Creating a Bing Maps (Virtual Earth) backend with custom pushpins

By Alan S. at June 29, 2010 02:10
Filed Under: Web / Software Development

Any web application using Bing Maps has to offer something specific to that site or program. For example, you might have a database of speed cameras for your city and want to offer your visitors a way to define search parameters and display the results with custom pushpin graphics.

 

Check out these reference books for Bing Maps, Google Earth, and Map Scripting:

 

The heart and soul of this functionality lies in a basic cross-platform Pushpin class that can be set up and populated using a C# backend, then passed to a JavaScript function that can read the generic data types in the class, parse them, and display the information.

   1: namespace App_Code
   2: {
   3:     public class Pushpin
   4:     {
   5:         private double latitude;
   6:         private double longitude;
   7:         private string title;
   8:         private string description;
   9:         private string imageUrl;
  10:  
  11:         public double Latitude
  12:         {
  13:             get { return latitude; }
  14:             set { this.latitude = value; }
  15:         }
  16:  
  17:         public double Longitude
  18:         {
  19:             get { return longitude; }
  20:             set { this.longitude = value; }
  21:         }
  22:  
  23:         public string Title
  24:         {
  25:             get { return title; }
  26:             set { this.title = value; }
  27:         }
  28:  
  29:         public string Description
  30:         {
  31:             get { return description; }
  32:             set { this.description = value; }
  33:         }
  34:  
  35:         public string ImageUrl
  36:         {
  37:             get { return imageUrl; }
  38:             set { this.imageUrl = value; }
  39:         }
  40:  
  41:         public Pushpin()
  42:         {
  43:             this.latitude = 0;
  44:             this.longitude = 0;
  45:             this.plancount = 0;
  46:             this.title = "";
  47:             this.description = "";
  48:             this.imageUrl = "";
  49:         }
  50:  
  51:         public Pushpin(double latitude, double longitude,
  52:             string title, string description, string imageUrl)
  53:         {
  54:             this.latitude = latitude;
  55:             this.longitude = longitude;
  56:             this.title = title;
  57:             this.description = description;
  58:             this.imageUrl = imageUrl;
  59:         }
  60:     }
  61: }

In the code above, we start by declaring a Namespace (App_Code). The Pushpin class has basic information like latitude, longitude, title, description, and an image URL (imageurl). Our C# backend will populate each of these values and return an array of Pushpin objects to the Javascript function our map page.

 

Next , we need to create a web service to accommodate our requests to populate the plot points of our speed camera locations. We create a SpeedCameraQueryService.asmx file that is empty except for providing an interface to our backend function:

   1: <%@ WebService Language="C#" CodeBehind="~/App_Code/SpeedCameraQueryService.cs" Class="SpeedCameraQueryService" %>
   2:  

And here is the corresponding SpeedCameraQueryService.cs file (placed in our App_Data directory).

   1: using App_Code;
   2: using System.Data;
   3:  
   4: [WebService]
   5: [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
   6: // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
   7: [ScriptService]
   8: public class SpeedCameraQueryService : WebService {
   9:  
  10:     [WebMethod]
  11:     public Pushpin[] GetAllInfo()
  12:     {
  13:         ArrayList ppArray = new ArrayList();
  14:         Pushpin pGeneric;
  15:         /* HERE IS WHERE YOU INSERT YOUR QUERY OR DATA READ */
  16:         /* When done, iterate thru your results... */
  17:         foreach (SpeedCamera.productRow r in MyDatatable)
  18:         {
  19:             pGeneric = new Pushpin( r.Lat,
  20:                 r.Long,
  21:                 r.Title,
  22:                 r.Description,
  23:                 "Images/plotpin2.png");
  24:             ppArray.Add(pGeneric);
  25:         }
  26:         Pushpin[] ia = (Pushpin[])ppArray.ToArray(typeof(Pushpin));
  27:         return ia;
  28:     }

Now, in our map.aspx file, we implement a Javascript function that is run when your users click a button on your webpage asking for the location of your speed cameras.

   1: var _PushpinLayer;
   2: _PushpinLayer = new VEShapeLayer();
   3: // our VEMap variable, map, gets the empty shape layer added
   4: // This line should go in your 'load' function that creates your map.
   5: map.AddShapeLayer(_PushpinLayer);
   6:  
   7: // Now we have the function that gets called when a user clicks
   8: // the button requesting to see our speed camera data.
   9: function PreviewPlots() {
  10:     var _totalRet = 0;
  11:     _PushpinLayer.DeleteAllShapes();
  12:     SpeedCameraQueryService.GetAllInfo(onGetComplete, onGetFailed);
  13:     function onGetComplete(result) {
  14:         PlotPreviewData(result);
  15:     }
  16:     function onGetFailed(result) {
  17:         alert("Error while connecting to the remote web service. Please try again later.");
  18:     }
  19: }
  20:  
  21: function PlotPreviewData(data) {
  22:     if (data == null)
  23:         return;
  24:     for (var i = 0; i < data.length; i++) {
  25:         var currPushpin = data[i];
  26:         var pushpinLocation = new VELatLong(currPushpin.Latitude, currPushpin.Longitude);
  27:         var shape = new VEShape(VEShapeType.Pushpin, pushpinLocation);
  28:         var customIconUrl = currPushpin.ImageUrl;
  29:         if (customIconUrl != "") {
  30:             shape.SetCustomIcon(customIconUrl);
  31:         }
  32:         shape.SetTitle(currPushpin.Title);
  33:         shape.SetDescription(currPushpin.Description);
  34:         _PushpinLayer.AddShape(shape);
  35:     }
  36: }

 

THE Definitive guide for Bing Maps! Now available on Amazon.com!

Click on the “Map Scripting 101” book at left to find out about this incredible book on map scripting covering Bing, Google, and Yahoo!

 

If you need assistance or have questions in setting up your application / web site to import KML files, please send us a message and we will schedule a call and let you know how we can help!

 

Bookmark and Share DotnetKicks dotnetshoutout

How to display KML / KMZ files using Bing Maps (Virtual Earth)

By Alan S. at June 24, 2010 08:21
Filed Under: Web / Software Development

 

 

kmlupload I’ve waited and waited for months now for Microsoft to add the popular KML / KMZ file formats directly to their library, but have seen no indication from them that it is coming anytime soon. This is a big deal for sites or desktop applications that offer Bing Maps, but can’t find a way for their visitors to display KML files on their local machines on your map page. The closest thing is a method by which you place the KML file on a publicly accessible web server, then call a Bing Maps remote function (passing it the URL of the file to be converted) and then displaying the returned results.

 

We decided to make the most of a good thing and create a simple way to allow our customers to display their local KML files on our publicly accessible embedded Bing Maps websites and applications. Microsoft requires that the KML to be decoded be Internet accessible so they can get the file, decode it with their proprietary methods, and simply return the data as a series of VEShape objects.

 

To accomplish this, our map software has an “Import KML” button that brings up a file selection dialog. The user selects the file which calls a server side C# function:

   1: WebClient wcUp = new WebClient();
   2: byte[] responseArray = wcUp.UploadFile("http://myserver.com/uploadkmlfile.aspx", tbFilename.Text);
   3: WebHeaderCollection myWebHeaderCollection = wcUp.ResponseHeaders;
   4: // Now read the filename from our header response
   5: string sNewFilename = myWebHeaderCollection.Get(0);
   6: mapBrowser.Document.InvokeScript("LoadKMLMap", new object[] { "http://myserver.com/KML_Temp/" + sNewFilename});

In line 2, we pass the URL of an .aspx file that exists on our server that handles the upload. Line 5 is important because it sets the variable sNewFilename to the unique name given the file on our server. Here is the sample UploadKMLFile.aspx and corresponding code so you can see what is happening:

   1: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="UploadKMLFile.aspx.cs" Inherits="UploadKMLFile" %>
   2: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
   3: <html xmlns="http://www.w3.org/1999/xhtml">
   4: <head runat="server">
   5:     <title></title>
   6: </head>
   7: <body>
   8:     <form id="form1" runat="server">
   9:     <div>
  10:     </div>
  11:     </form>
  12: </body>
  13: </html>

As you can see, the .aspx code is just a dummy page that relies on the C# code-behind to handle the upload:

   1: using System.IO;
   2: using System.Net;
   3: using System.Web;
   4:  
   5: public partial class UploadKMLFile : System.Web.UI.Page
   6: {
   7:     protected void Page_Load(object sender, EventArgs e)
   8:     {
   9:         foreach(string f in Request.Files.AllKeys) 
  10:         {
  11:             string sNewName = string.Format("{0}{1}{2}{3}{4}.kml",
  12:                     DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second, DateTime.Now.Millisecond);//file.FileName);
  13:             HttpPostedFile file = Request.Files[f];
  14:             file.SaveAs(Server.MapPath("~/KML_Temp/") + sNewName);
  15:             Response.Headers.Add("Newname", sNewName);
  16:         }
  17:     }
  18: }

The C# code behind (UploadKMLFile.aspx.cs) takes the file and saves it to a unique name in our ~/KML_Temp directory. We then add a response header which is the new name of the uploaded file. That name is then returned to the calling function on our map web page.

 

Line 6 of the first code block (server side C# function) then takes that returned new name and calls a JavaScript function on our map page called LoadKMLMap. That function looks like this:

   1: var lNew = new VEShapeLayer();
   2:  
   3: function LoadKMLMap(sFile)
   4: {
   5:     var veLayerSpec = new VEShapeSourceSpecification(VEDataType.ImportXML, sFile, lNew);
   6:     map.ImportShapeLayerData(veLayerSpec, onFeedLoad, true);
   7: }
   8:  
   9: function onFeedLoad(feed)
  10: {
  11:     var iCount=0;
  12:     for(var i=0;i<lNew.GetShapeCount();i++)
  13:     {
  14:         iCount++;
  15:         var shape = lNew.GetShapeByIndex(i);
  16:         if(shape.GetCustomIcon() == null) // we have no icon
  17:         {
  18:             shape.HideIcon();
  19:             shape.SetCustomIcon("<img src='http://upload.wikimedia.org/wikipedia/commons/c/ce/Transparent.gif' />");
  20:         }    
  21:     }
  22:     map.AttachEvent("onmouseover", ShapeInfo);
  23:     alert('KML collection loaded. There are '+ feed.GetShapeCount()+
  24:         ' items in this list. ' + iCount + ' actual');
  25: }
  26:  
  27: function ShapeInfo(e)
  28: {
  29:    if(e.elementID != null)
  30:    {
  31:       X = e.mapX;
  32:       Y = e.mapY;
  33:       var point = map.PixelToLatLong(new VEPixel(X,Y));
  34:       shape = map.GetShapeByID(e.elementID);
  35:       map.ShowInfoBox(shape, point);
  36:    }
  37: }

NOTES: Make sure to set the permissions on your KML_Upload directory so that IIS can write the stream to your server. The temporary filename given to each uploaded file ensures that the file is unique and that users looking at files of the same name on their machines will not have the same name on our server, thus avoiding conflict of files.

 

THE Definitive guide for Bing Maps! Now available on Amazon.com!

If you need assistance or have questions in setting up your application / web site to import KML files, please send us a message and we will schedule a call and let you know how we can help!

 

Bookmark and Share DotnetKicks dotnetshoutout


   

eMail Scraper
Generate email lists in seconds!


eSource Development presents the ultimate tool for email lead generation! They have decided to release the hottest email list generation tool that allows you to get hundreds (even THOUSANDS) of specific email addresses for any genre, niche, or geographical area.

Internet marketing companies and professionals have been using this tool for years. Now, it has been re-engineered, updated, and released to the public. This 'insider only' software was a closely guarded industry secret until recently.



Watch the Demo

NEW! Trial version available!

DOWNLOAD FOR FREE




  


Dr. Torgo's PC
System Inventory v2.0


Dr. Torgo's PC System Inventory offers a full range of system query options and powerful reporting tools. This software quickly generates reports on several dozen hives of system information including disks, CPU, memory, motherboard, users, ports, services, software, and MORE.

Read more here!

NEW! Trial version available!
DOWNLOAD FOR FREE


Help us out by visiting our sponsors!

Protect Your Business







Recent Comments

Comment RSS

What We're Playing





Who's Watchin' Me?