摘要:GoogleMap地址轉經緯度
//以下提供兩種GoogleMap的地址轉經緯度方法
(1) 後台的HttpRequest寫法
//Loc:實際地址
public string getLatlng(string Loc)
{
string str = "";
var url = String.Format("http://maps.google.com/maps/api/geocode/xml?sensor=false&address={0}", Loc);
string result = String.Empty;
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
using (var response = request.GetResponse())
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
//Json格式: 請參考http://code.google.com/intl/zh-TW/apis/maps/documentation/geocoding/
result = sr.ReadToEnd();
XmlDocument doc = new XmlDocument();
doc.LoadXml(result);
var nodes_1 = doc.GetElementsByTagName("location");
if (nodes_1.Count > 0)
{
var node_2 = (XmlElement)nodes_1[0];
var nodes_lat = ((XmlElement)node_2.GetElementsByTagName("lat")[0]).InnerText;
var nodes_lng = ((XmlElement)node_2.GetElementsByTagName("lng")[0]).InnerText;
//str = "(" + nodes_lat + "," + nodes_lng + ")";
str = nodes_lat + "," + nodes_lng;
}
}
return str;
}
(2)前端寫法--透過google.maps.Geocoder
//透過Google Geocoder將地址轉為經緯座標
function geocodeAjax(name, addr) {
var markers = [];
geocoder = new google.maps.Geocoder();
var c = 0;
//利用Deferred物件協助非同步呼叫全部完成的時機
var def = new jQuery.Deferred();
//geocoder似乎有使用量管控,若快速連續呼叫會停止運作
//在此使用setTimeout節流,每次查詢間隔一秒鐘
setTimeout(function () {
//呼叫decode(),傳入參數及Callback函數
geocoder.geocode({ address: addr }, function (results, status) {
//檢查執行結果
if (status == google.maps.GeocoderStatus.OK) {
var loc = results[0].geometry.location;
markers.push({
title: name + "@" + addr,
latlng: new google.maps.LatLng(loc.lat(), loc.lng())
});
//呼叫Deferred.resolve(),表示執行成功
def.resolve();
}
else {
//呼叫Deferred.reject(),表示執行失敗
def.reject();
}
});
}, c++ * 1000);
//傳回Promise物件,以協調非同步呼叫結果
return def.promise();
}