使用silverlight制作热点地图

参考文档:http://www.codeproject.com/Articles/49381/Silverlight-Creating-an-Image-Map-with-Hotspots

 目前网络上关于热点地图的实现大多数都是通过flash实现的,在这里我记录下通过silverlight实现的方法。

需求:

  1. MainPage加载时展示世界地图,鼠标移动大洲区域变色突出显示。
  2. 显示鼠标停留大洲所拥有的旅行线路条数,点击国家button进入相应搜索结果页。
  3. 点击大洲进入相应大洲的界面,该页面与MainPage类似,鼠标移入时显示结果略有不同,为该国家所拥有的线路名称与天数,即价格等。点击链接进入相应产品页。

 

截图如下:

 (MainPage)

 

 (大洲页,显示产品相关信息)

 

 开发工具:

visual studio 2010、Microsoft expression design4 (主要拿来切图用,即用钢笔工具描出国家或者大洲的边界,工具生成的代码可以直接用在xaml文件中,具体用法见此处http://www.codeproject.com/Articles/49381/Silverlight-Creating-an-Image-Map-with-Hotspots写的很详细)

 

关键部分代码:

实现鼠标移动时目标区域变色功能

?
void addMapEvents()
      {
          foreach (Canvas c in ( this .FindName( "map__matsuri" ) as Canvas).Children)
          {
              if (! string .IsNullOrEmpty(c.Name))
             
                  c.MouseMove+= new MouseEventHandler(on_mouseMove);
                 
                  c.MouseLeftButtonUp += new MouseButtonEventHandler(c_MouseLeftButtonUp);
              }
          }
      }

  绑定鼠标移动的事件(如需在页面加载后就有此功能需将addMapEvents方法添加到页面的构造函数当中)

?
void on_mouseMove( object sender, MouseEventArgs e)
        {
            Canvas c = sender as Canvas;
            ResetLastSelected();
            if (! string .IsNullOrEmpty(c.Name))
            {
                if (c.Name != lastSelected)
                {
                    HideMenu();
                }
                lastSelected = c.Name;
                SetupLinks();
                SetCanvasColor(c, Colors.Blue, 2, Colors.Black);
            }
 
           
            if (! string .IsNullOrEmpty(c.Name))
            {
                PopulateContextMenu(c.Name);
                PositionContextMenu(e.GetPosition(contextMenu.Parent as UIElement), true );
            }
           
        }

  鼠标移动,区域变色的具体实现。SetCanvasColor(c, Colors.Blue, 2, Colors.Black); 其中在世界地图这个层面这里的canvas即为每个大洲。看到这里应该就比较清楚了,这种实现方式就是把一个世界地图用expression design描出每一个大洲的边界(每一个大洲即为一个canvas)然后在鼠标移动的时候判断是在哪一个canvas上,并着色。

 

显示线路信息的解决办法

在这里分为两方面:

  1. silverlight读取数据库信息。
  2. 弹出/关闭菜单的动画效果。

关于silverlight读取数据库信息,开始我习惯性的找system.data,突然发现没有了(一番搜索之后才意识到silverlight是客户端程序不能直接访问数据库,一般都是采用webservice或是ria等访问的在本程序中我采用的是webservice这里没有太多可说的,需要注意的就是当修改了webservice服务中的方法后,silverlight端需要重新引用才能生效,否则会出现找不到新添加方法的情况。)

弹出/关闭菜单的动画效果代码如下,

 

?
<Storyboard x:Name= "HidePopup" >
      <DoubleAnimationUsingKeyFrames BeginTime= "0" Duration= "0" Storyboard.TargetName= "GridMenu" Storyboard.TargetProperty= "(UIElement.Opacity)" >
          <DiscreteDoubleKeyFrame KeyTime= "0" Value= "0" />
      </DoubleAnimationUsingKeyFrames>
  </Storyboard>
  <Storyboard x:Name= "ShowPopup" >
      <DoubleAnimationUsingKeyFrames BeginTime= "0" Storyboard.TargetName= "GridMenu" Storyboard.TargetProperty= "(UIElement.Opacity)" >
          <SplineDoubleKeyFrame KeyTime= "0" Value= "0" />
          <SplineDoubleKeyFrame KeyTime= "00:00:00.25" Value= "1" />
      </DoubleAnimationUsingKeyFrames>
  </Storyboard>

  同样的需要在后台绑定鼠标左键点击事件:LayoutRoot.MouseLeftButtonUp += new MouseButtonEventHandler(LayoutRoot_MouseLeftButtonUp);

然后显示的数据从数据库中读取,对button或者HyperlinkButton进行赋值即可。


原文地址:http://www.cnblogs.com/falcon-fei/archive/2012/08/06/2453531.html


Silverlight - Creating an Image Map with Hotspots

Introduction

Recently, I was working on a Silverlight application, and one of the pages had a graphic. One of the requirements was that the graphic should contain clickable regions (hotspots) and display a dynamic navigation menu when the end users click on it. An image that contains one or more hotspots or clickable areas is called an image map. I have put together a simple tutorial on how to get this done.

Getting Started

An image map can be created by using Microsoft Expression Design or Expression Blend.

  1. If you do not have Microsoft Expression Design, you can download a trial version from here.
  2. If you do not have Microsoft Expression Blend, you can download a trial version from here.

Microsoft Expression Designer

Prepare your favorite image. In this tutorial, I use a map graphic to demonstrate that we can create hotspots in different shapes with Microsoft Expression Designer/ Blend. I have downloaded a random map from here. Follow the steps from below.

  1. Open Microsoft Expression Design 3.
  2. Go to File, New, fill up all the information, and click on the OK button.
  3. Go to View, check Snap to Points and Snap to Pixels.
  4. File, Import Image, and browse for your image and click the Open button.
  5. Double click on Layer1 and rename it to MainImage.

At this point, you should see something like below:

Figure 1

Main Image

Add a new layer at the top of the MainImage layer, highlight it, and select the Pen tool and draw a hotspot around Russia.

Figure 2

New layer

Pen Tool

Russia

Double click Layer 2 and name it Russia or something meaningful so we can utilize it in the Silverlight application. Highlight the points and click on the Properties tab. See below:

Figure 3

Add property

Pick a color you like and set its opacity to 40%.

Figure 4

Set opacity

After you have finished drawing the hotspots, click on File, Export, and copy the setting from below.

Figure 5

Export

Putting everything together

Open Visual Studio 2008, go to File, New, Project, and choose the Silverlight Application template. If you don't have the Silverlight Controls Toolkit, you can download it from here. Make sure you have added the reference forSystem.Windows.Controls.Toolkit. Open MainPage.xaml and drag a Viewbox control on to the page. This control will stretch the map image inside it proportionally when we resize the browser. Then, copy the content inMapsHotSpot.xaml into the Viewbox content in MainPage.xaml. See below.

Listing 1
<UserControl x:Class="MapsHotspotDemo.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:controlsToolkit=
      "clr-namespace:System.Windows.Controls;
       assembly=System.Windows.Controls.Toolkit" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    mc:Ignorable="d" d:DesignWidth="640" 
    d:DesignHeight="480"> 
  <Grid x:Name="LayoutRoot">
        <controlsToolkit:Viewbox  x:Name="MapsViewbox"  >
<!-- Maps content here -->
           <Canvas 
              xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
              x:Name="MapsHotSpot" 
              Width="800" Height="600" 
              Clip="F1 M 0,0L 800,0L 800,600L 0,600L 0,0" 
              UseLayoutRounding="False">
           ...
           </Canvas>
<!-- End Maps content here -->
        </controlsToolkit:Viewbox>
  </Grid>
</UserControl>

Expression Blend

If you choose to do it by using Expression Blend, here are the steps to follow:

  1. Open Microsoft Expression Blend.
  2. Click on File, select New Project, and follow the setup from below.
Figure 6

Blend New Project

Add a Viewbox into the LayoutRoot and name it MapsViewbox, then add a Canvas inside the Viewbox and name itMapsHotspot. After that, add a Canvas to MapsHotspot and an Image control to the Canvas. From the Imagecontrol properties, specify the image source and setup the appropriate width and height of the image. Then, create another Canvas and name it Russia or something meaningful or unique. Make sure that the width and height of the newly created Canvas match the image in order to draw points on it. Click on the Pen tool and draw points or vertices around Russia. Pick a brush color and set its opacity to certain percentages. Repeat the same procedure for the rest of the countries.

Figure 7

Blend Hot Spot

Tooltips

Remember that we named each layer at the beginning. The layers and points are translated into Canvas and Pathobjects, respectively, when we export them into XAML. We can provide each layer with a unique name, or include a tagattribute to it and use it to pull the country information from a database or resource dictionaries. For simplification sake, we will have a method to loop through each child element in the MapsHotSpot, grab the name, and set it to the tooltip content. Attach a MouseMove event to each layer to highlight the country on mouse hover. Also, attach aMouseLeftButtonUp event to pop up a menu when the left mouse button is released. See Listing 2.

Listing 2
foreach (Canvas c in (this.FindName("MapsHotSpot") as Canvas).Children)
{
    if (!string.IsNullOrEmpty(c.Name))
    {
        c.Cursor = Cursors.Hand;
        ToolTip toolTip = new ToolTip { Content = c.Name };
        c.SetValue(ToolTipService.ToolTipProperty, toolTip);
        c.MouseMove += new MouseEventHandler(c_MouseMove);
        c.MouseLeftButtonUp += new MouseButtonEventHandler(c_MouseLeftButtonUp);
    }
}

Displayed below is the implementation of the c_MouseMove method. This method will highlights the Canvas/ country and clears the previous selection, if there is any, during the mouse hover event.

Listing 3
void c_MouseMove(object sender, MouseEventArgs e)
{
    Canvas c = sender as Canvas;
    ResetLastSelected();

    if (!string.IsNullOrEmpty(c.Name))
    {
        lastSelected = c.Name;
        SetCanvasColor(c, Color.FromArgb(255, 92, 112, 171), 2, Colors.Green);
    }
}

View in browser, you should see something like below. If you resize the browser, you will still see the full map. Place the mouse over the map image to see the tooltip and the highlighted region.

Figure 8

Preview

We will build a simple menu with several links in it. First, add a simple class to hold the link properties. See below for an example.

Listing 4
public class Links
{
    public string Title { get; set; }
    public string URL { get; set; }

    public Links(string t, string u)
    {
        Title = t;
        URL = u;
    }
}

After that, create a global List (T) class to hold the link objects, and populate the link class with the below data on page load.

Listing 5
private List<Links> _links = new List<Links>();

void SetupLinks()
{
    _links.Add(new Links("About the people", 
               "http://www.countryreports.org/{0}.aspx"));
    _links.Add(new Links("Economy", 
               "http://www.economicexpert.com/a/{0}.htm"));
    _links.Add(new Links("Global Statistics", 
               "http://www.geohive.com/cntry/{0}.aspx"));
    _links.Add(new Links("Population", 
               "http://www.geohive.com/charts/population1.aspx"));
    _links.Add(new Links("Wiki", 
               "http://en.wikipedia.org/wiki/{0}"));
}

Below is the implementation of the c_MouseLeftButtonUp method. This method will bring up the popup menu by calling the PopulateContextMenu method in response to the mouse left button click event. ThePopulateContextMenu takes a country name as an argument, loops through the list of link objects, and concatenates the country name to it. The purpose of the PositionContextMenu method is to set the popup menu position. I also added animation to fade in and fade out the popup menu, please refer to MainPage.xaml.

Listing 6
void c_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
    Canvas c = sender as Canvas;
    if (!string.IsNullOrEmpty(c.Name))
    {
        PopulateContextMenu(c.Name);
        PositionContextMenu(e.GetPosition(
                 contextMenu.Parent as UIElement), true);
        e.Handled = true;
    }
}

void PositionContextMenu(Point p, bool useTransition)
{
    if (useTransition)
        contextMenu.IsOpen = false;
    contextMenu.HorizontalOffset = p.X;
    contextMenu.VerticalOffset = p.Y;
    contextMenu.IsOpen = true;
}

void PopulateContextMenu(string country)
{
    contextListBox.Items.Clear();

    foreach (Links l in _links)
    {
        HyperlinkButton hlb = new HyperlinkButton();
        hlb.Content = l.Title;
        hlb.NavigateUri = new Uri(string.Format(l.URL, country));
        hlb.TargetName = "_blank";

        contextListBox.Items.Add(hlb);
    }   
}

At this point, you should see something like below:

Figure 9

Mouse click

The final piece is to hide the popup menu and clear the highlighted country once we click on the non- clickable area of the map image. In order to achieve that, we can attach a MouseLeftButtonUp event to the layout grid on page load. See below.

Listing 7
LayoutRoot.MouseLeftButtonUp += 
   new MouseButtonEventHandler(LayoutRoot_MouseLeftButtonUp);

void LayoutRoot_MouseLeftButtonUp(object sender, 
                MouseButtonEventArgs e)
{      
    ResetLastSelected();
    HideMenu();
}

void HideMenu()
{
    HidePopup.Begin();
    contextMenu.HorizontalOffset = -50.0;
}

Points of Interest

Initially, I was planning to use the right mouse button click event class that I found from here to trigger the popup menu, but I decided to leave it out after reading an article from here about its disadvantages.

I found this article useful although it was written in VB.NET and I can't get it to compile, but I'm able to utilize the logic embedded in it.

Conclusion

If you find any bugs or disagree with the contents, please drop me a line and I'll work with you to correct it. I would suggest downloading the demo and exploring it in order to grasp the full concept of it because I might have left out some useful information. I hope someone will find this article useful on how to create image hotspots or map on images.

Resources

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值