- public static double GetDistance(string origin, string destination, string apiKey) {
- double ret = 0;
- WebResponse response = null;
- try {
- string url = @"https://maps.googleapis.com/maps/api/distancematrix/json?origins=" +
- origin + "&destinations=" + destination + "&key=" + apiKey;
- HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
- response = request.GetResponse();
- Stream dataStream = response.GetResponseStream();
- StreamReader sReader = new StreamReader(dataStream);
- string jsonString = sReader.ReadToEnd();
- Debug.Write(jsonString);
- var jo = JObject.Parse(jsonString);
- JToken jt = jo.SelectToken("$.rows..elements..distance.value");
- ret = double.Parse(StringUtil.NullBlankToZero(jt.ToString()));
- return ret;
- } finally {
- response.Close();
- }
- }
例えば「origin:東京」-「destination:大阪」を指定してリクエストを投げると、以下の形式のJSONが返されるので、
JSONPathを使って、距離の部分を抜き出して戻り値にセットしています。
●例)「東京」-「大阪」間でリクエストを投げた時のJSON取得結果
- {
- "destination_addresses" : [ "Osaka, Osaka Prefecture, Japan" ],
- "origin_addresses" : [ "Tokyo, Japan" ],
- "rows" : [
- {
- "elements" : [
- {
- "distance" : {
- "text" : "513 km",
- "value" : 512545
- },
- "duration" : {
- "text" : "6 hours 16 mins",
- "value" : 22563
- },
- "status" : "OK"
- }
- ]
- }
- ],
- "status" : "OK"
- }
0 件のコメント:
コメントを投稿