【问题标题】:Google Map Integration, get measured distance谷歌地图集成,获取测量距离
【发布时间】:2012-02-25 21:25:56
【问题描述】:
您好,我正在开发 WinForms 中的运行日志。我想知道是否有人对谷歌地图集成有一些好的资源。最终目标是让用户双击“距离”列中的单元格,它将打开一个新表单。新表格上会有一个谷歌地图,用户可以使用谷歌的距离测量工具追踪他们的路线。接受该路线将关闭窗口并将追踪路线的距离(英里)输入到单元格中。
我对 Google 地图集成完全陌生,如果它实际上可以通过 C# 应用程序实现的话。请指出正确的方向,在那里我可以找到一些示例代码来实现我的目标。
提前致谢。
【问题讨论】:
标签:
c#
winforms
google-maps
google-api
【解决方案1】:
在你的项目中使用这个类来获取两个地方之间的距离
你可以从https://www.nuget.org/packages/newtonsoft.json/获取Newtonsoft.Json.Linq
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
namespace Management
{
class DeliveryMapInfo
{
string origin = @""; //Write the address of the origin here
public DeliveryMapInfo() { }
public int getDistanceTo(string destination)
{
System.Threading.Thread.Sleep(1000);
int distance = -1;
string url = "http://maps.googleapis.com/maps/api/directions/json?origin=" + origin + "&destination=" + destination + "&sensor=false";
string requesturl = url;string content = fileGetJSON(requesturl);
JObject _Jobj = JObject.Parse(content);
try
{
distance = (int)_Jobj.SelectToken("routes[0].legs[0].distance.value");
return distance / 1000;// Distance in KMS
}
catch
{
return distance / 1000;
}
}
protected string fileGetJSON(string fileName)
{
string _sData = string.Empty;
string me = string.Empty;
try
{
if (fileName.ToLower().IndexOf("http:") > -1)
{
System.Net.WebClient wc = new System.Net.WebClient();
byte[] response = wc.DownloadData(fileName);
_sData = System.Text.Encoding.ASCII.GetString(response);
}
else
{
System.IO.StreamReader sr = new System.IO.StreamReader(fileName);
_sData = sr.ReadToEnd();
sr.Close();
}
}
catch { _sData = "unable to connect to server "; }
return _sData;
}
}
}
您的很多想法取决于您要使用的 API,即。距离矩阵、方向、地理编码等。
注意:“/directions/”
我发现方向是我使用的最完整的 api,因为它可以进行地理编码、查找距离、查找持续时间……等等。
但是,方向 JSON 文件的大小比其他 JSON 文件大。
用你的判断力。
string url = "http://maps.googleapis.com/maps/api/directions/json?origin=" + origin + "&destination=" + destination + "&sensor=false";
和
distance = (int)_Jobj.SelectToken("routes[0].legs[0].distance.value");
例如:
Directions JSON 文件中的结构是:
-Routes
- Bound
- NorthEast
- SouthWest
- Copyrights
- Legs
- Steps
- duration
- distance
- endlocation
- maneuver
- htmlinstructions
- polyline
- startlocation
- travelmode
- Distance
- text
- value
- Duration
- text
- value
- StartAddress
- EndAddress
- EndLocation
- lat
- lng
- StartLocation
- lat
- lng
- Overview Polyline
- Summary
- Warnings
- Waypoint Order
- Status