Quantcast
Channel: Envato Tuts+ Code - Mobile Development
Viewing all articles
Browse latest Browse all 1836

Android SDK: Working with Google Maps – Map Setup

$
0
0

With the Google Maps Android API, you can build apps with localization features. In this series, we are creating an Android app in which the user’s location is presented on a map, as are nearby places of interest. In this part we will use the GoogleMap class to show the user location and also to control how the map presents itself to the user. We will also create custom map markers!

This is the second of four parts in a tutorial series on Using Google Maps and Google Places in Android apps:

Remember that the app we are creating in this series will not function on an Android emulator, only on an actual device!

App We Are Working Towards
This is a snapshot of the final app.

1. Create the User Interface Elements

Step 1

When we display the map, we will place Markers on top of it. These Markers will indicate the user location and nearby places of interest. When you add a Marker to a GoogleMap, you can configure various aspects of it, including the text that appears on it and the icon displayed. For this app, we will use the following collection of icons. Feel free to download and use them (you can also find them in the source code download for this tutorial):

User Location Marker
User location Marker icon
Blue Marker
Blue place marker icon
Red Marker
Ref place marker icon
Green Marker
Green place marker icon
Purple Marker
Purple place marker icon

The yellow icon indicates the user’s location. We will use the other colors to mark places of particular types in the area. When you fetch place data from Google Places API, each place is associated with one or more category types. For the purposes of this tutorial series, we are going to fetch places listed with the following types: food, bar, store, museum, and art gallery. We will use the red icon to indicate food, blue for drink, green for shopping, and purple for all other places returned. You will of course be able to alter the types of places your app returns if you wish.

Place your Marker icons in the drawables folder(s) for your app.

Step 2

Now we can bring these into the Activity code so that we can refer to them as part of the user interface. In your app’s main Activity add the following instance variables, which we will use to store the drawable resource ID values for each Marker icon:

private int userIcon, foodIcon, drinkIcon, shopIcon, otherIcon;

Inside the onCreate method after the existing code, initialize these variables:

userIcon = R.drawable.yellow_point;
foodIcon = R.drawable.red_point;
drinkIcon = R.drawable.blue_point;
shopIcon = R.drawable.green_point;
otherIcon = R.drawable.purple_point;

We will refer to these when we add the Markers to the map.


2. Create a GoogleMap Object

Step 1

For the code we’ll use in the rest of this tutorial, you need to add the following import statements to your Activity class:

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import android.location.Location;
import android.location.LocationManager;
import android.content.Context;

We’ve placed a map in the app’s main Activity by including a Map Fragment in the layout file, but at the moment we have no control over it in the Java code. Let’s get a reference to it as a GoogleMap object now. In your Activity class add an instance variable for it:

private GoogleMap theMap;

In the onCreate method after the existing code, add a conditional to check whether the map has been instantiated (in case we already have it when onCreate executes after the first run):

if(theMap==null){
    //map not instantiated yet
}

The remainder of the onCreate processing will be placed in this conditional block. Inside it, first try to get the map from the Fragment Manager:

theMap = ((MapFragment)getFragmentManager().findFragmentById(R.id.the_map)).getMap();

We’ll pass the ID we gave the Map Fragment in the layout XML, cast it to a MapFragment object and attempt to retrieve the GoogleMap object from it. If the Google Play services resources are not available on the user device, this will return null, so add another conditional before proceeding:

if(theMap != null){
    //ok - proceed
}

Now we know the app will not attempt to carry out map processing if the required packages are not installed on the user device.

Step 2

Now we can carry out manipulations on the map using the GoogleMap class. Let’s start by setting the map type. We can choose from satellite, terrain, normal, and hybrid, which correspond to the options you see in the Google Maps app itself. Let’s go for hybrid:

theMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

Here is an overview of the map types:

Hybrid
Hybrid
Normal
Normal
Satellite
Satellite
Terrain
Terrain

At this stage you can experiment by running the app with the different map types set. As an advanced project, you could add a user interface control to let the user choose between the types.


3. Display the User Location

Step 1

The app will display the user’s last recorded location. Since it carries out this process more than once, when the app first runs and then when the user’s location changes, we will place the code in a helper method. Add the following method outline after your onCreate method:

private void updatePlaces(){
//update location
}

Up at the top of the class, add the following variable to represent a Location Manager instance:

private LocationManager locMan;

Back in the updatePlaces method, attempt to retrieve this:

locMan = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

Now we can use this to retrieve the user’s last recorded location:

Location lastLoc = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

We will need the longitude and latitude to mark this location on the map, so retrieve them now as double variables:

double lat = lastLoc.getLatitude();
double lng = lastLoc.getLongitude();

We can wrap these in a LatLng object to pass to the map Marker object we will create soon:

LatLng lastLatLng = new LatLng(lat, lng);

Step 2

Now we have the user’s last known longitude and latitude, so we can use this information to mark the location on the map. To do this we will use a Marker object. Since the user location is going to be continually updated, let’s add an instance variable at the top of the class declaration to represent its Marker:

private Marker userMarker;

Back inside updatePlaces, let’s first check whether the Marker has already been instantiated, in which case we can remove it:

if(userMarker!=null) userMarker.remove();

This will mean that after the first time the Marker is added to the map, when the user’s location is updated, the app will remove the previous Marker so that it can be replaced with one representing the updated location. Now let’s instantiate the Marker. You can pass various settings to the Marker class, including the location details and the display details, such as icon and text labeling. Create the Marker and add it to the map:

userMarker = theMap.addMarker(new MarkerOptions()
	.position(lastLatLng)
	.title("You are here")
	.icon(BitmapDescriptorFactory.fromResource(userIcon))
	.snippet("Your last recorded location"));

Take a moment to look over this code. First we instruct the map object to add a new Marker, instantiating the new Marker object at the same time. We pass the latitude and longitude position, a text string for the title, the user location icon we created and set as a instance variable, then a text string snippet which will appear when the user taps the Marker.

Step 3

Now that we have the user’s position marked, let’s animate the map camera to zoom in on the location. This time we’ll use the GoogleMap object, calling the animateCamera method:

theMap.animateCamera(CameraUpdateFactory.newLatLng(lastLatLng), 3000, null);

We pass a camera update comprising the user location, a duration value, and null for the optional callback method parameter.

Now we can call the new helper method, which we will add more code to later. Back in your onCreate method, after setting the map type:

updatePlaces();

You can run your app now to zoom in on the last recorded location on your device. It’s also worth exploring the available methods for setting options with the GoogleMap object and for zooming to locations. You can also add overlays to the map with methods for various shapes and other visual elements.

User Location
User Location

Conclusion

In this tutorial, we explored how to manipulate the map object and created icons for our location Markers. We also retrieved and displayed the user location, zooming to it when the app runs. In the next two parts of the series, we will setup API access for Google Places and pass the user’s location to retrieve nearby places of interest. We will place additional Markers on the map to display information about these places, updating as the user moves around. Although we have a specific set of functionalities in mind for this app, you may wish to explore the possibilities for the various mapping and location classes as we go along, as there are many features available to experiment with!


Viewing all articles
Browse latest Browse all 1836

Trending Articles