[ASP.net WebForm/Google] Google Map标记点(Marker)更改图示、加入对话框/API 3版

[ASP.net WebForm/Google] Google Map标记点(Marker)更改图示icon、加入对话框/API 3版

延续上一篇文章:[ASP.net WebForm/Google] 在Google Map上放置多个标记地点(Marker)/API 3版

这次要想办法把Marker更改icon

(顺道一提,我一直以为使用Google Map API的话,网站一定要对外开放,目前发现只要本机电脑网络有通

有引用 就可以玩了)

另外,为了配合项目需求,程序有稍做重构且追加DB数据


Create database GoogleMapDB
Go
Use GoogleMapDB
Go
/*在C#的纬度经度类型为double,在SQL Server的类型为float
  参考:http://stackoverflow.com/questions/1440620/which-sql-server-data-type-best-represents-a-double-in-c
*/
Create table tb_company
(
 id int identity primary key,/*主键*/
 zip_no int,/*邮递区号*/
 company_title nvarchar(50),/*公司名称*/
 [address] nvarchar(500),   /*公司地址*/
 lat float default(0) ,     /*公司所在纬度*/
 lng float default(0) ,     /*公司所在经度*/
 company_desc nvarchar(50),/*公司简介*/
 iconName varchar(50) /*标记点的icon文件名*/
)
Go
Insert into tb_company (zip_no,company_title,[address],company_desc,iconName) values
(100,‘精诚资讯‘,‘中国台北市中正区罗斯福路2段100号‘,‘在恒逸资讯上过课的日子受您照顾了‘,‘flower.jpg‘),
(100,‘中国台湾师范大学‘,‘中国台北市和平东路一段162号‘,‘在捷运古亭站附近的大学‘,‘bar.jpg‘),
(100,‘捷运古亭站‘,‘中国台北市中正区罗斯福路2段164-1号‘,‘南京松山线啥时会开?‘,‘airplane.jpg‘)

 

新增一个DBUtil.cs类,做为数据存取层


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Data;
using System.Data.SqlClient;

///

/// DBUtil 的摘要描述
/// 

public class DBUtil
{

    //连线字符串
    string connStr = WebConfigurationManager.ConnectionStrings["connStr"].ConnectionString;

    ///

    /// 传入SQL语句,回传DataTable对象
    /// 

    ///
    ///
    public DataTable queryDataTable(string sql)
    {

        DataSet ds = new DataSet();
        using (SqlConnection conn=new SqlConnection(this.connStr))
        {
            SqlDataAdapter da = new SqlDataAdapter(sql,conn);
            da.Fill(ds);
        }
        return ds.Tables.Count > 0 ? ds.Tables[0] : new DataTable();
    }

}

用来输出JSON字符串的getSpot.ashx



using System;
using System.Web;
/*要引用以下的命名空间*/
using System.Data;
using System.Data.SqlClient;
using System.Net;
using System.IO;
/*Json.NET相关的命名空间*/
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

public class getSpot : IHttpHandler {

    int zip_no = 100;//中正区的邮递区号
    DBUtil db = new DBUtil();

    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        if (!string.IsNullOrEmpty(context.Request["zip_no"]))
        {
            int.TryParse(context.Request["zip_no"], out this.zip_no);//防SQL Injection,转类型失败就用默认值
        }

        //取得DataTable原始数据
        DataTable dt = db.queryDataTable(@"SELECT zip_no,company_title,address,company_desc,iconName,lat,lng
                                            from tb_company
                                            Where zip_no="[email protected]"
                                            Order by ID ASC");
        //因为本范例的数据都没有纬度和经度,所以把原始数据DataTable传入取得一个新的DataTable(有纬度、经度的)
        DataTable dt_new  = this.fillLatLng(dt);
        //利用Json.NET将DataTable转成JSON字符串,请参考另一篇文章:http://www.dotblogs.com.tw/shadow/archive/2011/11/30/60083.aspx
        string str_json = JsonConvert.SerializeObject(dt_new, Formatting.Indented);
        context.Response.Write(str_json);
    }

    ///

    /// 回传有纬度和经度的DataTable
    /// 

    ///
     private DataTable fillLatLng(DataTable dt)
    {

        DataTable dt_new = dt.Copy();
        for (int i=0;i
/// 传入JSON字符串,取得经纬度 /// /// /// private double[] getLatLng(string json) { JObject jo = JsonConvert.DeserializeObject(json); //从results开始往下找 JArray ja = (JArray)jo.Property("results").Value; jo = ja.Value(0);//JArray第0笔 //得到location的JObject jo = (JObject)((JObject)jo.Property("geometry").Value).Property("location").Value; //纬度 double lat = Convert.ToDouble(((JValue)jo.Property("lat").Value).Value); //经度 double lng = Convert.ToDouble(((JValue)jo.Property("lng").Value).Value); double[] latLng= {lat,lng}; return latLng; } /// /// 把地址转成JSON格式,这样资讯里才有经纬度 /// 因为使用到地理编码技术,请注意使用限制:http://code.google.com/intl/zh-TW/apis/maps/documentation/geocoding/#Limits /// /// /// private string convertAddressToJSONString(string address) { //var url = "http://maps.google.com/maps/api/geocode/json?sensor=false&address=" + HttpContext.Current.Server.UrlEncode(address); //2012.4.12 以上是旧写法,新写法请用以下 var url = "http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=" + HttpContext.Current.Server.UrlEncode(address); string result = String.Empty; HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); using (var response = request.GetResponse()) using (StreamReader sr = new StreamReader(response.GetResponseStream())) { result = sr.ReadToEnd(); } return result; } public bool IsReusable { get { return false; } } }

执行结果:

Default.aspx的jQuery Ajax和Google Map API写法都稍做修改,容易阅读



Default.aspx.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

/*Code-Behind没什么要做的*/
public partial class _Default : System.Web.UI.Page
{
    protected string zip_no = "100";

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)//Get Method要做的事
        {

        }

    }

}

执行Default.aspx结果:

环境都准备好了,开始动工

更改icon图示很简单只要加上以下粗体字就行了



执行结果:

接着针对点击Click每个标记点,就要出现对话框

这边如果真的照Google API 范例写


  var map;
        //在某一区加入多个标记点
        function addMarker(str_json)
        {
           //是否为第一次执行循环
           var first = true;    

            for (var index in str_json)
            {

            //建立纬经度座标对象
            var latlng = new google.maps.LatLng(str_json[index].lat, str_json[index].lng);

                if (first == true)
                {//第一次执行循环
                    /*以哪个纬经度中心来产生地图*/
                    var myOptions = {
                        zoom: 14,
                        center: latlng,
                        mapTypeId: google.maps.MapTypeId.ROADMAP
                    };
                    /*产生地图*/
                    map = new google.maps.Map($("div#div_showMap")[0], myOptions);

                    first = false;
                } //End if (first == true) 

                //加入一个Marker到map中
                var imageUrl = "";//空字符串就会使用默认图示
                if(str_json[index].iconName!="")//有值
                {
                //可以是相对路径也可以是http://开头的绝对路径,路径错误的话图示不会出来
                    imageUrl = "images/" + str_json[index].iconName;
                }

                var marker = new google.maps.Marker({
                    position: latlng,
                    map: map,
                    title: str_json[index].company_title,
                    icon:imageUrl
                });

                /*资讯窗口*/
               var infowindow = new google.maps.InfoWindow({content:str_json[index].company_desc}); 

                google.maps.event.addListener(marker, ‘click‘, function() {
                  infowindow.open(map,marker); });
            } //End for (var index in str_json)
        }//End function addMarker()

会发现不论点击哪个标记点,对话框(资讯窗口)都在同一个位置,且内文都一样

所以参考此篇做Bug修正:Google Maps API v3 – Multiple Markers, Multiple Infowindows

完整的Default.aspx



执行结果:

完整研究包

2011.12.02 追记,标记点一次最多似乎只能标10个?2013.02.01 追记:[ASP.net WebForm/Google] 解决Google API地理编码技术地址转JSON要求上限10笔问题

另外Marker是可以自订属性的,例如以下粗体字


              //加入一个Marker到map中
                var marker = new google.maps.Marker({
                    position: latlng,
                    map: map,
                    title: str_json[index].通讯地址,
                    html: str_json[index].称谓,
                    LABOR_ID:str_json[index].LABOR_ID
                });

                 //为每个标记点注册click事件
               google.maps.event.addListener(marker, ‘click‘, function() { 

                  /*this就是指marker,当click标记点时,超链接导向其他页*/
                  window.location.href = "persondetail.html?LABOR_color: blue;">this.LABOR_ID;

                   });//End click function

2011.12.03 追记一个自己写的类,专门处理Google Map API业务


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.IO;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Data;

///

/// Create by Shadow at 2011.12.03
/// 参考文章:http://www.dotblogs.com.tw/shadow/archive/2011/02/18/21442.aspx
/// http://www.dotblogs.com.tw/shadow/archive/2011/12/02/60381.aspx
/// http://www.dotblogs.com.tw/shadow/archive/2011/12/02/60479.aspx
/// 

public class GoogleMapUtility
{

    ///

    /// 回传有纬度和经度的DataTable
    /// 

    ///
    public static DataTable fillLatLng(DataTable dt, string addressColumnName)
    {
        /*先把原始结构和数据Copy到一份新的DataTable*/
        DataTable dt_new = dt.Copy();
        dt_new.Columns.Add("lat", typeof(double));
        dt_new.Columns.Add("lng", typeof(double));

        for (int i = 0; i
/// 传入Geocoding API产生的地址JSON字符串,取得经纬度 /// /// /// public static double[] getLatLng(string json) { JObject jo = JsonConvert.DeserializeObject(json); //从results开始往下找 JArray ja = (JArray)jo.Property("results").Value; jo = ja.Value(0);//JArray第0笔 //得到location的JObject jo = (JObject)((JObject)jo.Property("geometry").Value).Property("location").Value; //纬度 double lat = Convert.ToDouble(((JValue)jo.Property("lat").Value).Value); //经度 double lng = Convert.ToDouble(((JValue)jo.Property("lng").Value).Value); double[] latLng = { lat, lng }; return latLng; } /// /// 把地址转成JSON格式,这样资讯里才有纬经度 /// 因为使用到Geocoding API地理编码技术,请注意使用限制:http://code.google.com/intl/zh-TW/apis/maps/documentation/geocoding/#Limits /// /// /// public static string convertAddressToJSONString(string address) { //var url = "http://maps.google.com/maps/api/geocode/json?sensor=false&address=" + HttpContext.Current.Server.UrlEncode(address); //2012.4.12 以上是旧写法,新写法请用以下 var url = "http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=" + HttpContext.Current.Server.UrlEncode(address); string result = String.Empty; HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); using (var response = request.GetResponse()) using (StreamReader sr = new StreamReader(response.GetResponseStream())) { result = sr.ReadToEnd(); } return result; } }

使用方法(以.ashx为例)



using System;
using System.Web;
/*要引用以下的命名空间*/
using System.Data;
using System.Data.SqlClient;
using System.Net;
using System.IO;
/*Json.NET相关的命名空间*/
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
//如何于泛型处理常式 .ashx 中存取工作阶段变量(Session Variable)
using System.Web.SessionState;
//http://www.limingchstudio.com/2009/05/ashx-session-variable.html
public class GetPeopleMapData : IHttpHandler, IRequiresSessionState
{

    public void ProcessRequest (HttpContext context) {

        context.Response.ContentType = "text/plain";
        //从DB取得DataTable原始数据
        DataTable dt = new DataTable();
        //假设因为数据都没有纬度和经度,所以把原始数据DataTable传入此方法再取得一个新的DataTable(有纬度、经度的)
        DataTable dt_new  = GoogleMapUtility.fillLatLng(dt,"address");//字符串address为数据表的地址字段名称
        //利用Json.NET将DataTable转成JSON字符串,请参考另一篇文章:http://www.dotblogs.com.tw/shadow/archive/2011/11/30/60083.aspx
        string str_json = JsonConvert.SerializeObject(dt_new, Formatting.Indented);
        context.Response.Write(str_json);//输出JSON字符串
    }

    public bool IsReusable {
        get {
            return false;
        }
    }

}

2012.2.3 追记 衍伸阅读文章:

[C#.NET][NetWork] 如何利用 JSON API 分析 IP Location

2012.4.12 要注意默认标记点是张img图片

今天发现ART人员定义了一个CSS模式

#div_showMap img{padding:6.5em 7.2em;}

在IE8上浏览的话,标记点会消失

然后再补一个Google地理编码专用,用来检查回传Result结果状态是否为OK字符串


///

    /// 传入json字符串,判断回传结果Result是否为OK
    /// 

    ///
    ///
    private static bool isResultOk(string json)
    {
        JObject jo = JsonConvert.DeserializeObject(json);

        return jo["status"].ToString().ToUpper() == "OK";
    }

原文:大专栏  [ASP.net WebForm/Google] Google Map标记点(Marker)更改图示、加入对话框/API 3版

原文地址:https://www.cnblogs.com/chinatrump/p/11458441.html

时间: 2024-08-28 08:43:29

[ASP.net WebForm/Google] Google Map标记点(Marker)更改图示、加入对话框/API 3版的相关文章

解析ASP.NET WebForm和Mvc开发的区别

解析ASP.NET WebForm和Mvc开发的区别 2013-12-29 01:59 30052人阅读 评论(9) 收藏 举报  分类: ASP.NET(14)  版权声明:本文为博主原创文章,未经博主允许不得转载. 因为以前主要是做WebFrom开发,对MVC开发并没有太深入的了解.自从来到创新工场的新团队后,用的技术都是自己以前没有接触过的,比如:MVC 和EF还有就是WCF,压力一直很大.在很多问题都是不清楚的情况下,问周围的人,别人也只是给自己讲一个大概.而且前两天因为问了一个比较细的

利用Bootstrap+Avalonjs+EntityFramework 开发ASP.NET WebForm应用程序(上)

本文将介绍如何利用Bootstrap+Avalonjs+EntityFramework 开发ASP.NET WebForm应用程序,分为上下两篇.上篇主要介绍实现,下篇主要介绍界面. 打开Visual Studio Web Express2013新建一个空白应用程序 ContactSample--联系人示例 (1)数据库 引入界面文件BootStrap,JS文件jquery和avalon,建立联系人页面Contact.aspx. 打开数据库,设计数据库ContactSample,数据库比较简单,

ASP.NET WebForm中用async/await实现异步出人意料的简单

1. 在.aspx中添加异步标记 <%@ Page Language="C#" Async="true"%> 2. 在.aspx.cs或者.ascx.cs(用户控件)中添加异步方法 private async Task GetMyPosts() { var posts = await ServiceFactory.BlogPostSevice.GetBlogPostsPagedAsync(); rpPosts.DataSource = posts; rp

【Ext.Net学习笔记】01:在ASP.NET WebForm中使用Ext.Net

Ext.NET是基于跨浏览器的ExtJS库和.NET Framework的一套支持ASP.NET AJAX的开源Web控件,包含有丰富的Ajax运用,其前身是Coolite. 下载地址:http://www.ext.net/download/示例地址:http://examples.ext.net/ 1.首先下载Ext.Net,地址:http://www.ext.net/download/ ,有两种框架选择,选择下载WebForms 当前版本是2.5.1,压缩包里面包含了不同版本,分别用在相应.

ASP.NET WebForm / MVC 源码分析

浏览器 Url:https//localhost:6565/Home/Index ,https//localhost:6565/WebForm1.aspx,请求服务器(构建请求报文,并且将请求报文发送给服务器) 1:服务器(内核模式 Http.sys)对请求报文做基本的处理 2:请求服务器(用户模式,IIS服务器) 2.1:对发送过来的数据做一个检查,如果请求的是静态资源的(.html,jpg,js),那么IIS直接将这些资源返回浏览器 2.2:如果是动态资源(.aspx,.ashx),IIS服

性能工具MiniProfiler在Asp.Net WebForm跟踪EntityFramework

http://www.xuebuyuan.com/356638.html 选择MiniProfiler.EF 默认会把MiniProfiler安装上,笔者程序是Asp.Net WebForm 不需要安装MiniProfiler.MVC3 2: 在Global.asax中添加下面代码: void Application_BeginRequest(){if (Request.IsLocal){ MiniProfiler.Start();}} void Application_EndRequest()

Ext.Net学习笔记01:在ASP.NET WebForm中使用Ext.Net

Ext.Net是一个对ExtJS进行封装了的.net控件库,可以在ASP.NET WebForm和MVC中使用.从今天开始记录我的学习笔记,这是第一篇,今天学习了如何在WebForm中使用Ext.Net控件库. 下载Ext.Net 首先要去Ext.Net网站上下载Ext.Net,我先学习的是WebForm版: 当前版本是3.1.0,压缩包里面包含了不同版本,分别用在相应.net版本的程序中. 在项目中引用 要使用Ext.Net,首先创建一个WebForm程序,我们这里使用4.5版. 在引用管理器

ASP.Net WebForm温故知新学习笔记:一、aspx与服务器控件探秘

开篇:毫无疑问,ASP.Net WebForm是微软推出的一个跨时代的Web开发模式,它将WinForm开发模式的快捷便利的优点移植到了Web开发上,我们只要学会三步:拖控件→设属性→绑事件,便可以行走于天下.但这样真的就可以走一辈子吗?实际上,ASP.Net经常被喷的诟病就在于WebForm以及只会拖控件的ASP.Net程序员,往往大型互联网系统也没有采用WebForm的模式进行开发.但是,WebForm并不是一无是处,而是我们没有用好,还有很多东西我们知其然不知其所以然,现在我们就来对这些平

ASP.Net WebForm的发布(图解)

全文包括如下三部分内容: 方式一.发布网站至默认的IIS路径下 方式二.发布网站至指定的IIS路径下 注:发布过程中可能出现的错误信息及解决方法 ---------------------------------------------------------------------------------------------------------- 方式一.发布网站至默认的IIS路径下 1)发布环境:Windows 7 旗舰版 + IIS 7.5 + VS2010 + ASP.Net W