Building Mobile Apps with Google Maps Android API v2
Illustration by Don Barnett

Start your free trial now, and begin learning software, business and creative skills—anytime, anywhere—with video instruction from recognized industry experts.

Start Your Free Trial Now

Video: Drawing lines

The Google Android SDK includes tools for drawing on the map. You can create circles, polygons and lines, and I'll start in this demo by showing how to draw a simple line between two points. In this version of my project, named Drawing Lines I've added two fields to the main activity class. They're called marker1, and marker2, and they're both data typed as the Marker class. Then, in the method where I'm adding a marker, I've added some logic.
Expand all | Collapse all
  1. 9m 51s
    1. Welcome
      52s
    2. What you should know before watching this course
      3m 50s
    3. Using the exercise files
      5m 9s
  2. 18m 55s
    1. Understanding the Maps API terms of service
      3m 51s
    2. Setting up the developer tools
      3m 33s
    3. Connecting and testing an Android device
      5m 45s
    4. Using the SDK documentation
      2m 22s
    5. Demonstrating the finished apps
      3m 24s
  3. 33m 49s
    1. Adding required permissions to a project
      6m 53s
    2. Getting a Google Maps API key
      8m 9s
    3. Importing and linking the Google Play services library
      3m 46s
    4. Checking the device for the Google Play services APK
      9m 4s
    5. Displaying your first map
      5m 57s
  4. 51m 13s
    1. Displaying a map with MapView
      6m 36s
    2. Getting a reference to the map object
      5m 35s
    3. Setting a map's initial state in the layout
      6m 26s
    4. Setting a map's initial state programmatically
      6m 42s
    5. Geocoding an address to get its coordinates
      8m 10s
    6. Changing between different types of map objects
      4m 23s
    7. Maintaining map state between activity restarts
      13m 21s
  5. 21m 3s
    1. Enabling the My Location button
      6m 26s
    2. Getting the current location programatically
      8m 16s
    3. Listening for current location updates
      6m 21s
  6. 38m 47s
    1. Adding map markers
      4m 52s
    2. Removing map markers
      4m 5s
    3. Customizing marker icon graphics
      4m 55s
    4. Displaying default info windows
      1m 53s
    5. Customizing marker info windows
      8m 49s
    6. Handling marker events
      7m 59s
    7. Dragging and dropping markers
      6m 14s
  7. 24m 54s
    1. Drawing lines
      8m 48s
    2. Drawing polygons
      8m 3s
    3. Drawing circles
      8m 3s
  8. 31m 21s
    1. Reviewing the tour finder application
      4m 19s
    2. Adding a map fragment to an activity
      11m 54s
    3. Passing the current location to another mapping app
      7m 31s
    4. Displaying Google Play services license terms
      5m 2s
    5. Preparing the app for distribution
      2m 35s
  9. 27s
    1. Next steps
      27s

please wait ...
Watch the Online Video Course Building Mobile Apps with Google Maps Android API v2
3h 50m Intermediate Aug 07, 2013

Viewers: in countries Watching now:

Maps make mobile apps more useful; they can help users find businesses and areas of interest, get directions, or gain insights into new communities. In this course, learn to add interactive maps to your Android apps with Google Maps Android API v2. David Gassner first shows you how to set up the tools, get an API key, and import and link to Google Play services. After an introduction to presenting simple maps with the MapView and MapFragment classes, the course describes how to set a map's initial state, switch between different map types, work with map markers, draw shapes, and work with zoom controls, the My Location button, and various user gestures. Finally, learn to add a map to an existing app and prepare it for distribution.

Note: An Android device with Android 3.0 (Honeycomb) or higher, and that has Google Play Store installed, is required to use the course exercises. (Kindle Fire and Nook devices do not qualify.) Finished mapping apps can be deployed on Android 2.2 (Froyo) or later.

Topics include:
  • Setting up the developer tools
  • Adding required permissions
  • Getting a Google Maps API key
  • Importing and linking the Google Play services
  • Setting a map's initial state
  • Geocoding an address
  • Getting the current location programmatically
  • Adding map markers
  • Handling marker events
  • Drawing lines, polygons, and circles
  • Adding maps to existing apps
Subject:
Developer
Software:
Android
Author:
David Gassner

Drawing lines

The Google Android SDK includes tools for drawing on the map. You can create circles, polygons and lines, and I'll start in this demo by showing how to draw a simple line between two points. In this version of my project, named Drawing Lines I've added two fields to the main activity class. They're called marker1, and marker2, and they're both data typed as the Marker class. Then, in the method where I'm adding a marker, I've added some logic.

This is the setMarker method down towards the bottom of the class. After creating the marker options object, I then take a look and see which markers have already been created. If marker1 is null, then I create it. But if that marker is already on the map, I check to see if marker2 is null, and if it isn't, I create that. And finally, if both markers have been created, I remove them and then recreate marker1 again. So now I'm going add a little bit of code that will be executed right here after I've created both markers.

And I will draw a line between the two markers. I'll place the cursor after the call to addMarker for marker2, and I'll type in a call to a new method that doesn't exist yet, drawLine. Then, I'll press Ctrl 1, and select Create method drawLine. Then, I'll Ctrl click and jump to the new method. If you're working on Mac, press Cmd and click. The first step to creating a line is to create an instance of the class PolylineOptions.

I'll type in the name of the class, and then make sure I have an import for it. And I'll name the object options, then I'll instantiate the object with the constructor method, new PolylineOptions. The PolylineOptions class is very similar to marker options, in that, it has a set of methods that you can call one after the other. Each of these methods returns a reference to the options object. And so you can daisy chain the calls to the methods and do them all in a single statement.

Going back down to my new method. I'll place the cursor on the next line, and notice I'm not placing a semicolon at the end of the line. I'm continuing the current statement. When you draw a line on the map, it's actually called a polyline, and it can have multiple segments. When you add two points you are drawing a single line. Three points would create two segments, four would create three segments, and so on. For each point, call the add method and pass in an instance of the lat long class.

There's also a version of the add method where you can pass in a set of lat longs all at once. But I'll just use the first version. The add method expects a latlong object, and I'll get that by calling marker1.getPosition, the method that returns the latlong of the marker. Then, I'll duplicate that line of code and for the second version, I'll set it to marker2, and I'll complete the statement. That's all the information I need to provide to create the simple line, and now I'll actually create the line and add it to the map by calling the addpolyline method of the map object.

Be sure to call addpolyline and not addpolygon. I'll pass in the options object, and the line will be added to the map. I'll run the application, and test this version. I'm working directly on the device, so you'll be able to see where I touch the screen. And I'll touch in one location and hold for a moment. That creates my first marker. I'll touch in a second location. And that creates the second marker, and adds the line. Now there are a couple of issues to take care of.

The first, is that the line doesn't appear to line up with the markers. It's a little bit too far down. And here's why. When you add a marker to the map, Google Maps expects the bottom of the marker to line up with the location. Not the center. And you can see this easily by going back to the Google Maps default marker. I'll go back up to my set marker method, and I'm going to comment out this line of code that's using the custom marker and uncomment the line that's using the default marker.

I'll run the application. And I'll once again add a couple of markers, and this time, the lines directly touch the bottoms of the markers, as expected. So if you want to use an icon, like my custom icon, that is expecting to hit the center of the location, you have to say so when you add the marker to the map, and here's how. I'll go back to my setMarker method, and I'll reverse my comments, so I'm using my custom marker, and then I'll add a method call to the MarkerOptions statement, of .anchor.

The anchor method expects two float values, and I'll pass in .5f, and .5f. Here's the logic. Imagine a rectangular grid, where your icon appears. A value of zero comma zero is the upper left corner of the grid. And one comma one is the lower right corner. So 0.5 and point 0.5 is the direct center of the anchor. I'll save and run that code. And let's see the difference.

I'll touch and hold once, touch and hold again and now the ends of my line directly hit the center of the target, as I want. Here's the second issue I'll describe and show you the solution to. I have a single line, but my code allows me to wipe out these markers and place two new markers. So when I touch and hold a third time, and then again, I'm actually creating another line and the first line is orphaned. So, I need to add code to make sure that I only have one line at a time.

Here's how I'll do it. I'll go back to my draw line method and I'll save a reference to the line that I am creating. With polyline line equals, and then I'll get the reference from the call to addPolyline. I'll be sure to add an import for that class, and save. Now, I need to be able to reference that line object in other methods. I'm going to take this declaration of the polyline and copy it to the clipboard.

Then I'll get rid of the class declaration here and then go back up to the top of my class and declare this as a field right after the markers. And that will cause the line reference to persist for the lifetime of the activity. Now I'll go back down here and add quote to the removed everything method. After I removed the markers from the map, I'll then remove the line, if you like you can set it to no, but it's not really necessary because the next time you call draw a line, the line field will be reused and the original reference will be released.

I'll run the application again, and I'll create an initial line, and then I'll create another new line. And so on and so forth. So now the code says you can only have one line at a time. Finally, I'll describe how to customize the appearance of the line. It's black by default, and has a width of ten screen-dependent pixels. You can modify both of those values when you create the line. I'll go back to my drawLine method, and I'll call two new methods of the PolylineOptions class.

First I'll call .color, and I'll pass in a color constant from the color class of android dot graphics, and I'll pass in blue. And then I'll set a width, and I'll use a value of five, The default is ten, so this will be half the default width. I'll run the application one more time, and there's my new line. I touch and hold, touch and hold and so on.

There are other things that you can affect about lines and other shapes. For lines that cover a large part of the planet you can set a line to being geodesic, meaning that it will follow the curve of the planet. And you can also set the z-index of the shape, affecting where the line appears relative to labels and other visual elements of the map. I encourage you to experiment with lines and other shapes that I'll show you in subsequent movies.

Find answers to the most frequently asked questions about Building Mobile Apps with Google Maps Android API v2 .


Expand all | Collapse all
please wait ...
Q: In the Chapter 2 movie "Checking the device for the Google Play services APK," when I create my first Google Maps app, the app crashes when I call the custom method servicesOK(). The error in LogCat starts with:
 
"java.lang.IllegalStateException: The meta-data tag in your app's AndroidManifest.xml does not have the right value."
 
How do I fix this? 
A: The latest version of the Google Play services library has a new required meta-data tag in the app manifest. Add the following tag within the <application> tag:
 
<meta-data
     android:name="com.google.android.gms.version"
     android:value="@integer/google_play_services_version" /> 
 
After rebuilding the app, the error should be resolved. 
 
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ .

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

* Estimated file size

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed Building Mobile Apps with Google Maps Android API v2.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member ?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferences from the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Learn more, save more. Upgrade today!

Get our Annual Premium Membership at our best savings yet.

Upgrade to our Annual Premium Membership today and get even more value from your lynda.com subscription:

“In a way, I feel like you are rooting for me. Like you are really invested in my experience, and want me to get as much out of these courses as possible this is the best place to start on your journey to learning new material.”— Nadine H.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.