Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add direction of the route on the google map?

Tags:

c#

google-maps

I have two connected points on the map and I want to know which one is startpoint and endpoint so I want to add direction(arrows) of the route. How can I do it using c#? This is my code:

PointLatLng start1 = new PointLatLng(42.252938, 42.680411);
PointLatLng end1 = new PointLatLng(42.256321, 42.675658);
GDirections dir1;
var path1 = GMapProviders.GoogleMap.GetDirections(out dir1, start1, end1, false, false, true, true, true);
GMapRoute route1 = new GMapRoute(dir1.Route, "path1");
route1.Stroke.Color = Color.Red;
GMapOverlay lay1 = new GMapOverlay("route1");
lay1.Routes.Add(route1);
map.Overlays.Add(lay1);
like image 988
Leri Gogsadze Avatar asked Oct 30 '22 02:10

Leri Gogsadze


1 Answers

You need to send a web request to google maps api.

In order to do this, you may follow these steps :

Create a web request in C# and pass start and endpoint as parameters , have a look at code snippet below (also refer docs here)

Pay special attention to this part (This is what you need to use) :

If you pass coordinates, they are used unchanged to calculate directions. Ensure that no space exists between the latitude and longitude values. origin=41.43206,-81.38992

string gMapsUrl = @"https://maps.googleapis.com/maps/api/directions/json?origin=42.252938,42.680411&destination=42.256321,42.675658&key=YOUR_API_KEY";

WebRequest directionReq = WebRequest.Create(gMapsUrl);

WebResponse directionResponse = directionReq.GetResponse();

Stream data = directionResponse.GetResponseStream();

StreamReader reader = new StreamReader(data);

// get json-formatted string from maps api
string responseFromServer = reader.ReadToEnd();

response.Close();

Notice how i used this :

origin=42.252938,42.680411&destination=42.256321,42.675658

in request URL.

Also refer this SO post for sample response Also use using System.Net; in your class for using WebRequest

Follow this SO post for constructing webRequests

like image 52
Ankit Avatar answered Nov 15 '22 05:11

Ankit