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

时间:2019-09-04
本文章向大家介绍[ASP.net WebForm/Google] Google Map标记点(Marker)更改图示、加入对话框/API 3版,主要包括[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


<%@ WebHandler Language="C#"  %>

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="+this.zip_no+@"
                                            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写法都稍做修改,容易阅读


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default"
    Debug="true" %>




    
    
    
    
    


    

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图示很简单只要加上以下粗体字就行了


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default"
    Debug="true" %>




    
    
    
    
    


    

执行结果:

接着针对点击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


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default"
    Debug="true" %>




    
    
    
    
    


    

执行结果:

完整研究包

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 < dt.Rows.Count; i++)//走访原始数据
        {
            string json_address = GoogleMapUtility.convertAddressToJSONString(dt.Rows[i][addressColumnName].ToString());
            //取得纬度和经度
            double[] latLng = GoogleMapUtility.getLatLng(json_address);
            dt_new.Rows[i]["lat"] = latLng[0];
            dt_new.Rows[i]["lng"] = latLng[1];

        }


        return dt_new;
    }


    /// 
    /// 传入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为例)


<%@ WebHandler Language="C#"  %>

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