Drawing a Line/Path on Google Maps

Drawing a line/path on Google Maps

Thank you for your help. At last I could draw a line on the map.
This is how I done it:

/** Called when the activity is first created. */
private List<Overlay> mapOverlays;

private Projection projection;

public void onCreate(Bundle savedInstanceState) {

linearLayout = (LinearLayout) findViewById(R.id.zoomview);
mapView = (MapView) findViewById(R.id.mapview);

mapOverlays = mapView.getOverlays();
projection = mapView.getProjection();
mapOverlays.add(new MyOverlay());


protected boolean isRouteDisplayed() {
return false;

class MyOverlay extends Overlay{

public MyOverlay(){


public void draw(Canvas canvas, MapView mapv, boolean shadow){
super.draw(canvas, mapv, shadow);

Paint mPaint = new Paint();

GeoPoint gP1 = new GeoPoint(19240000,-99120000);
GeoPoint gP2 = new GeoPoint(37423157, -122085008);

Point p1 = new Point();
Point p2 = new Point();
Path path = new Path();

Projection projection=mapv.getProjection();
projection.toPixels(gP1, p1);
projection.toPixels(gP2, p2);

path.moveTo(p2.x, p2.y);

canvas.drawPath(path, mPaint);

How do I draw a route, along an existing road, between two points?

Indeed, you can draw precise route in Google Maps Android API using results provided by Directions API web service. If you read the documentation for Directions API you will see that response contains information about route legs and steps. Each step has a field polyline that is described in the documentation as

polyline contains a single points object that holds an encoded polyline representation of the step. This polyline is an approximate (smoothed) path of the step.

So, the main idea to solve your issue is to get response from Directions API, loop through route legs and steps, for each step get encoded polyline and decode it to the list of coordinates. Once done you will have a list of all coordinates that compound the route, not only begin and end point of each step.

For simplicity I recommend using the Java client library for Google Maps Web services:


Using this library you can avoid implementing your own async tasks and decoding function for polylines. Read the documentation to figure out how to add the client library in your project.

In Gradle it should be something similar to

compile 'com.google.maps:google-maps-services:(insert latest version)'
compile 'org.slf4j:slf4j-nop:1.7.25'

I have created a simple example to demonstrate how it works. Have a look at my comments in the code

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

private GoogleMap mMap;
private String TAG = "so47492459";

protected void onCreate(Bundle savedInstanceState) {
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()

public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;

LatLng barcelona = new LatLng(41.385064,2.173403);
mMap.addMarker(new MarkerOptions().position(barcelona).title("Marker in Barcelona"));

LatLng madrid = new LatLng(40.416775,-3.70379);
mMap.addMarker(new MarkerOptions().position(madrid).title("Marker in Madrid"));

LatLng zaragoza = new LatLng(41.648823,-0.889085);

//Define list to get all latlng for the route
List<LatLng> path = new ArrayList();

//Execute Directions API request
GeoApiContext context = new GeoApiContext.Builder()
DirectionsApiRequest req = DirectionsApi.getDirections(context, "41.385064,2.173403", "40.416775,-3.70379");
try {
DirectionsResult res = req.await();

//Loop through legs and steps to get encoded polylines of each step
if (res.routes != null && res.routes.length > 0) {
DirectionsRoute route = res.routes[0];

if (route.legs !=null) {
for(int i=0; i<route.legs.length; i++) {
DirectionsLeg leg = route.legs[i];
if (leg.steps != null) {
for (int j=0; j<leg.steps.length;j++){
DirectionsStep step = leg.steps[j];
if (step.steps != null && step.steps.length >0) {
for (int k=0; k<step.steps.length;k++){
DirectionsStep step1 = step.steps[k];
EncodedPolyline points1 = step1.polyline;
if (points1 != null) {
//Decode polyline and add points to list of route coordinates
List<com.google.maps.model.LatLng> coords1 = points1.decodePath();
for (com.google.maps.model.LatLng coord1 : coords1) {
path.add(new LatLng(coord1.lat, coord1.lng));
} else {
EncodedPolyline points = step.polyline;
if (points != null) {
//Decode polyline and add points to list of route coordinates
List<com.google.maps.model.LatLng> coords = points.decodePath();
for (com.google.maps.model.LatLng coord : coords) {
path.add(new LatLng(coord.lat, coord.lng));
} catch(Exception ex) {
Log.e(TAG, ex.getLocalizedMessage());

//Draw the polyline
if (path.size() > 0) {
PolylineOptions opts = new PolylineOptions().addAll(path).color(Color.BLUE).width(5);


mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(zaragoza, 6));

Please note that for web service you have to create a separate API key, the API key with Android app restriction won't work with web service.

The result of my example is shown in screenshot

Android Sample Image 16

You can also download a complete sample project from


Don't forget replace the API key with yours.

I hope this helps!

how to draw path between 2 points on google map

you can use the latest google api


thre are lot of links available for this. take a look on

Drawing a line/path on Google Maps

How to Draw Route in Google Maps API V2 from my location

Android: How to draw route directions google maps API V2 from current location to destination

How to draw a path as a straight line in google maps?

Isn't straight what is given in the official docs, as well?

Still, Here is a fiddle for you to play with.

var mapOptions = { zoom: 2, center: new google.maps.LatLng(0, 60) };
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var path = [
new google.maps.LatLng(10,20),
new google.maps.LatLng(0,40),
new google.maps.LatLng(50,60)];
var pathOptions = { path: path, strokeColor: "red", strokeWeight: 2 }
var myPath = new google.maps.Polyline(pathOptions);

How to draw line on google maps

The simplest way is to use a GMSPolyline.

Assuming you have a coordinates array of CLLocationCoordinate2D's and they are in the correct order.

let path = GMSMutablePath()
for coord in coordinates {
let line = GMSPolyline(path: path)
line.strokeColor = UIColor.blue
line.strokeWidth = 3.0
line.map = self.map

drawing a line path in google map with GPS co-ordinates

try this


function initialize(){
var center= new google.maps.LatLng(10.012869,76.328802);
var myOptions = {
zoom: 18,
center: center,
mapTypeControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.HYBRID
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

var polylineCoordinates = [
new google.maps.LatLng(10.013566,76.331549),
new google.maps.LatLng(10.013566,76.331463),
new google.maps.LatLng(10.013503,76.331313),
new google.maps.LatLng(10.013482,76.331205),
new google.maps.LatLng(10.013419,76.330926),
new google.maps.LatLng(10.013334,76.330712),
new google.maps.LatLng(10.013313,76.330411),
new google.maps.LatLng(10.013292,76.330175),
new google.maps.LatLng(10.013228,76.329854),
new google.maps.LatLng(10.013144,76.329553),
new google.maps.LatLng(10.013059,76.329296),
new google.maps.LatLng(10.012996,76.329017),
new google.maps.LatLng(10.012869,76.328802),
new google.maps.LatLng(10.012785,76.328545),
new google.maps.LatLng(10.012700,76.328223),
new google.maps.LatLng(10.012679,76.328030),
new google.maps.LatLng(10.012658,76.327837),
new google.maps.LatLng(10.012637,76.327600),
new google.maps.LatLng(10.012573,76.327322),
new google.maps.LatLng(10.012552,76.327043),
new google.maps.LatLng(10.012552,76.326807),
new google.maps.LatLng(10.012510,76.326613),
new google.maps.LatLng(10.012447,76.326399),
new google.maps.LatLng(10.012404,76.326227),
var polyline = new google.maps.Polyline({
path: polylineCoordinates,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2,
editable: true




draw different route line between multiple markers maps

Currently you are stringing all the results together in a single polyline. The directions service is asynchronous, the results may come back in a different order than sent. One solution is to make each independent directions result a separate polyline. If you need them combined into a single polyline, you need to keep track of the order and put them together in the correct order.

  • related question: Inconsistent behaviour drawing a route between two points in Google Maps v3
  • related question: Remove straight line in google map path using javascript

proof of concept fiddle

code snippet:

var geocoder;var map;
function initialize() { var map = new google.maps.Map( document.getElementById("map_canvas"), { center: new google.maps.LatLng(37.4419, -122.1419), zoom: 13, mapTypeId: google.maps.MapTypeId.ROADMAP }); var lat_lng = [ new google.maps.LatLng(19.449045, -99.1588115), new google.maps.LatLng(19.54951, -99.20688), new google.maps.LatLng(19.4219738, -99.0992125), new google.maps.LatLng(19.446199, -99.1609357), new google.maps.LatLng(19.54578,-99.206918), new google.maps.LatLng(19.503391,-99.201939)
]; for (var t = 0; (t + 1) < lat_lng.length; t++) { //Intialize the Direction Service var service = new google.maps.DirectionsService(); var directionsDisplay = new google.maps.DirectionsRenderer();
var bounds = new google.maps.LatLngBounds(); if ((t + 1) < lat_lng.length) { var src = lat_lng[t]; var des = lat_lng[t + 1]; service.route({ origin: src, destination: des, travelMode: google.maps.DirectionsTravelMode.DRIVING }, function(result, status) { if (status == google.maps.DirectionsStatus.OK) { // new path for the next result var path = new google.maps.MVCArray(); //Set the Path Stroke Color // new polyline for the next result var poly = new google.maps.Polyline({ map: map, strokeColor: '#4986E7' }); poly.setPath(path); for (var k = 0, len = result.routes[0].overview_path.length; k < len; k++) { path.push(result.routes[0].overview_path[k]); bounds.extend(result.routes[0].overview_path[k]); map.fitBounds(bounds); } } else alert("Directions Service failed:" + status); }); } }}google.maps.event.addDomListener(window, "load", initialize);
html,body,#map_canvas {  height: 100%;  width: 100%;  margin: 0px;  padding: 0px}
<script src="https://maps.googleapis.com/maps/api/js"></script><div id="map_canvas"></div>

Related Topics

Leave a reply