[C#/ASP.net] 經緯度轉行政區 (利用Google反地理編碼)

[C#/ASP.net] 經緯度轉行政區 (利用Google反地理編碼)


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

using System;
using System.Web;
using System.IO;
using System.Net;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

//傳入緯度、經度,回傳行政區
public class ConvertLatlngToDistrict : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";

        string latlng = context.Request["latlng"];
          
        
        if (!string.IsNullOrEmpty(latlng))
        {
            string url =
            "http://maps.googleapis.com/maps/api/geocode/json?latlng="+latlng+"&sensor=true";
            string json = String.Empty; 
             
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            //指定語言,否則Google預設回傳英文
            request.Headers.Add("Accept-Language","zh-tw");
             
            using (var response = request.GetResponse())
            using (StreamReader sr = new StreamReader(response.GetResponseStream()))
            {
             
                json = sr.ReadToEnd();
                 
            }
            JObject obj = (JObject)JsonConvert.DeserializeObject(json);
            string status =  obj["status"].ToString();
            if (status=="OK")
	        {
                JArray ary = (JArray)obj["results"];
                ary = (JArray)ary[0]["address_components"];

               
                var q = from o in ary
                        where o["types"][0].ToString()=="locality" && o["types"][1].ToString()=="political" 
                        select o;

                string district = q.FirstOrDefault()["long_name"].ToString();
                
                context.Response.Write("{\"District\":\""+district+"\"}");
	        }
             
            
             
        }
        

    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}

 

呼叫範例:

image