Get entity by property in Bing Maps V7

Every once in a while a question comes up on the forums around how to extend the functionality of the map controls. A simple example of one such request was the ability to get a tile layer by name. In Bing Maps v6.3 we had functionality that allowed us to do this. In Bing Maps v7 this functionality was removed as it wasn’t really needed and could easily be recreated if someone wanted it. When I came across this forum question I decided to do a quick code write up on how to do this and realized that it made more sense to provide something a bit more flexible. So, I extended this idea and have wrote a simple method that allows you to get any entity by any public property. I also decided add the ability to specify the collection to look inside of so it could be used with a single entity collection if you wanted to find an entity inside of a particular collection without searching all collections.

This is easily accomplished because JavaScript supports anonymous properties. We can easily add a custom property to an object simply by adding a reference to the customer property. The following code sample has this method for getting an entity by property. In addition the following code sample also implements this method to add the ability to get a layer by name like we were able to do in Bing Maps v6.3.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
   <head>
      <title></title>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

      <script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

      <script type="text/javascript">
         var map;

         function GetMap()
         {
            // Initialize the map
            map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),{
                credentials: "Bing Maps Key", 
                center: new Microsoft.Maps.Location(48.03,-122.4), 
                zoom: 12, 
                mapTypeId: Microsoft.Maps.MapTypeId.road 
            }); 

            // Create the tile layer source
            var tileSource = new Microsoft.Maps.TileSource({
                uriConstructor: 'http://www.microsoft.com/maps/isdk/ajax/layers/lidar/{quadkey}.png'
            });

            // Construct the layer using the tile source
            var tilelayer = new Microsoft.Maps.TileLayer({ mercator: tileSource, opacity: .7 });

            //Create a custom Property to store the layer name
            tilelayer.LayerName = "MyLayer";

            // Push the tile layer to the map
            map.entities.push(tilelayer);
         }

         //Method that will get a layer or entity by name assuming it has a LayerName property on it.
         function GetLayerByName(layerName){
            return GetEntityByProperty(map.entities, 'LayerName', layerName);
         }

         //This Method is similar to the above but more flexible and allows you to get a layer based on the value of any public property.
         function GetEntityByProperty(collection, propertyName, propertyValue){
            var len = collection.getLength(), entity;

            for(var i = 0; i < len; i++){
                entity = collection.get(i);

                if(entity[propertyName] && entity[propertyName] == propertyValue){
                    return entity;
                }else if (entity.getLength){
                    //Entity collections have this property and we want to look inside these collections
                    var layer = GetEntityByProperty(entity, propertyName, propertyValue);

                    if(layer != null){
                        return layer;
                    }
                }
            }

            return null;
         }

         //Simple method that toggle the visibility of a layer 
         function ToggleLayerVisibility(layerName){
            var layer = GetLayerByName(layerName);

            if(layer){
                layer.setOptions({ visible : !layer.getVisible() });
            }
         }
      </script>
   </head>
   <body onload="GetMap();">
        <div id='mapDiv' style="position:relative; width:400px; height:400px;"></div><br/>
        <input type='button' onclick="ToggleLayerVisibility('MyLayer')" value="Get Layer by Name and toggle visibility"/>
   </body>
</html>
Advertisements

6 thoughts on “Get entity by property in Bing Maps V7

  1. Very cool. It makes good sense to do it this way. less overhead. One type-o in your code.

    This line;

    should look like this;

    The trailing /> is missing the / from the tag.

    Thanks Ricky!

    • Thanks for asking. It has been an interesting path that lead me to here. Many years ago, I had worked on some Bing Maps projects but got bored of the technology after 6 months and thought I knew all I needed in that area (ignorance). I ha to keep working with the technology and decided that I should find something about it that interests me. In my case I have a background in physics and mathematics, so I started seeing how I could leverage my knowledge form there with what I was doing with Bing Maps. I started answering questions on forums and I didn’t know a whole lot about Bing Maps at the time, but found that by answering questions on the forums I came across more scenarios that I likely would not have come across on my own and was learning just how much I didn’t know about mapping and how much more interesting it is than I originally thought. I started blogging about some of the basic things I was discovering and learning about Bing Maps as I tried things out and over time others stated finding those useful. I eventually tried presenting at a small conference and as scary as it seemed being new to that, it was also very exciting and had some great conversations with others who were interested in the technology afterwards. After a few years I was nominated to be a Microsoft MVP which is an award Microsoft gives out to community leaders of their tech. My work already knew I was good with maps, but when I became an MVP, they considered me an expert. I’ve been working with the Bing Maps tech for over 10 years now and still come across new scenarios in which maps are being used in cool and interesting ways all the time. I joined Microsoft 6 years ago as a technical sales specialist for Bing Maps for two reasons; I loved working with it, and I felt that the team wasn’t focused and building what developers wanted and I wanted to change that. About three years ago we formed the Bing Maps customer advisory team which bridges the gap between developers/customers and the Bing Maps engineering team. We drive a lot of the product roadmap and align it to the needs of developers/customers based on conversations we have had. Something as simple as asking a question on the forums in the past year has led to about 30 new features of the Bing Maps V8 web control most of which are designed to make it easier to develop with. I was lucky enough a couple years ago to be the lead program manager for the Bing Maps V8 web control. I worked very closely with the engineering team and dictated a lot of the developer interface to ensure that it made sense and was easy to use. I even wrote early prototypes of some of the features such as the spatial math, data binning and GeoXml modules which the engineering team simply cleaned up and integrated into the platform. With all of this, I still spend an average of 1.5 hours a day answering questions on the forums because I find it to be an invaluable source of insight into what developers are trying to do with the platform, and I also enjoy helping others solve problems. If you want to become an expert, find something about the technology that interests you that might eventually turn it into your passion. Do you have any strengths in other areas that you can bring to the technology, for me it was math/physics, but it could be anything, like if you are an expert in Angular, then maybe initially focus on showing interesting ways to use Bing Maps in angular. There are a lot of different ways to get involved in the community; forums, blogs, open source projects, presenting at events, writing books are some of the most common and many community leaders usually do several of these at some point in their career. The most important part is make sure you are having fun, otherwise what’s the point :)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s