呼叫百度地圖API進行地理編碼和反地理編碼(一)
阿新 • • 發佈:2019-02-11
前段時間有師兄希望幫忙做一個類似於地理編碼之類的東西,就是在表格裡輸入經緯度以後可以通過程式實現地理位置的批量輸出,自己寫了半天也沒寫出來,
在當時實習的專案經理(於老師)的指導下我才明白什麼意思,程式碼也都是他寫的,特此宣告。
介面設計:
使用說明:在上面兩個Text文字框分別輸入緯度和緯度,第三個Text文字框會輸出地址;
在上面兩個Text文字框分別輸入地址,第三個Text文字框會輸出緯度和緯度;
點選"地理編碼"後觸發事件:
private void button2_Click(object sender, EventArgs e) { string url = "http://api.map.baidu.com/geocoder/v2/?ak=Y4NcP7YcxEkiwSuYedq5vW09&output=json&address=" + this.textBox2.Text + "&city=" + this.textBox1.Text; WebClient wc = new WebClient(); Stream stream = wc.OpenRead(url); StreamReader sr = new StreamReader(stream); string strLine = ""; while ((strLine = sr.ReadLine()) != null) { JsonObject js = JsonObject.Parse(strLine) as JsonObject; if (js["status"].ToString()=="0") { string result = "經度:"; result += js["result"]["location"]["lat"]; result += ",緯度:" + js["result"]["location"]["lng"]; this.textBox4.Text = result; } } sr.Close(); }
說明:使用Json格式傳輸資料,呼叫
點選"逆地理編碼"後觸發事件:
private void button1_Click(object sender, EventArgs e) { string url = "http://api.map.baidu.com/geocoder/v2/?ak=Y4NcP7YcxEkiwSuYedq5vW09&output=json&location=" + this.textBox1.Text + "," + this.textBox2.Text + "&pois=0"; WebClient wc = new WebClient(); Stream stream = wc.OpenRead(url); StreamReader sr = new StreamReader(stream); string strLine = ""; while ((strLine = sr.ReadLine()) != null) { JsonObject js = JsonObject.Parse(strLine) as JsonObject; if (js["status"].ToString() == "0") { string result = "地址:" + js["result"]["formatted_address"]; this.textBox4.Text = result; } } sr.Close(); } }