---
title: "Google Map Directions"
author: "huhu_long"
date: "2012-09-15T03:20:05Z"
tags: []
categories: ["编程语言"]
slug: "google-map-directions"
draft: false
lastmod: "2012-09-15T03:30:58Z"
id: 1678997
url: "https://vrplat.iteye.com/blog/1678997"
---

First time try google map related, the requirement asks to provide a step by step route for sales, so that they are easy to work with them.

So first design the API.


```C#

    [operationcontract]
    GetDirectionResponse GetDirection(GetDirectionRequest request);

    [datacontract]
    public class GetDirectionRequest : BaseServiceRequest
    {
        [datamember]
        public ServiceAddress Origin { get; set; }

        [datamember]
        public ServiceAddress Destination { get; set; }

        [datamember]
        public bool? Sensor { get; set; }

        [datamember]
        public GMapTravelMode? Mode { get; set; }

        public static implicit operator GetDirectionReqt(GetDirectionRequest request)
        {
            return new GetDirectionReqt
            {
                Origin = request.Origin,
                Destination = request.Destination,
                Sensor = request.Sensor ?? false,
                Mode = request.Mode ?? GMapTravelMode.Driving
            };
        }
    }

    [datacontract]
    public class GetDirectionResponse : BaseServiceResponse
    {
        [datamember(name = "routes")]
        public List<GMapRoute> Routes { get; set; }

        [datamember(name = "status")]
        public string Status { get; set; }

        public static implicit operator GetDirectionResponse(GetDirectionResp response)
        {
            return new GetDirectionResponse
            {
                Status = response.Status,
                Routes = response.Routes,

                IsSuccess = response.IsSuccess,
                ErrorMessage = response.ErrorMessage
            };
        }
    }

```


Then the implementation (there is another layer between service and helper class, skip here...)

```C#

public GetDirectionResp GetDirection(GetDirectionReqt request)
        {
            return GMapHelper.QueryRoute(request.Origin, request.Destination, request.Mode, request.Sensor);
        }

```


And the GMapHelper code

```C#

public static GetDirectionResp QueryRoute(ServiceAddress origin, ServiceAddress destination, GMapTravelMode travelMode = GMapTravelMode.Driving, bool sensor = false)
        {
            var gmapRouteQueryUrl = ConfigurationManager.AppSettings["gmap_route_query_url"];
            var requestUri = new Uri(string.Format(gmapRouteQueryUrl, origin, destination, travelMode, sensor.ToString().ToLower()));
            var response = new GetDirectionResp();

            try
            {
                var responseData = new WebClient().DownloadData(requestUri);
                var serializer = new DataContractJsonSerializer(typeof(GetDirectionResp));
                var stream = new MemoryStream(responseData, false);

                response = (GetDirectionResp)serializer.ReadObject(stream);

                if (response.Status == "OK")
                {
                    response.IsSuccess = true;
                }
                else
                {
                    response.IsSuccess = false;
                    response.ErrorMessage = string.Format("Unable to get route(s) from {0} to {1}.", origin, destination);
                }
            }
            catch (Exception ex)
            {
                string errMessage = string.Format("Unexpected exception getting route(s) from {0} to {1}", origin, destination);
                Logger.Error(string.Format("{0}: {1}", MethodBase.GetCurrentMethod().Name, errMessage), ex);

                response.IsSuccess = false;
                response.ErrorMessage = string.Format("{0}, Message: {1}", errMessage, ex.Message);
            }

            return response;
        }

```


oh, almost forget the google map directions request url:


```xml

<!-- Google Map -->
<add key="GMap_Route_Query_URL" value="http://maps.google.com/maps/api/directions/json?origin={0}&amp;destination={1}&amp;mode={2}&amp;sensor={3}" />

```


And attach some official material web sites.
<https://developers.google.com/maps/documentation/webservices/index>
<https://developers.google.com/maps/documentation/directions/>

The other thing about usage limits

> 
> Use of the Google Directions API is subject to a query limit of 2,500 directions requests per day. Each directions search will count as a single request against your daily quota when the mode of transportation is driving, walking or cycling. Searching for transit directions will count as 4 requests.
>