Developing Android Applications with Google Maps API: Current Location, Nearby Places, and Route Planning

Dec 06, 2025 · Programming · 10 views · 7.8

Keywords: Google Maps API | Android Development | Location Services | Nearby Places Search | Route Planning

Abstract: This article provides a comprehensive guide to integrating Google Maps API in Android applications for current location tracking, nearby place searches (e.g., police stations), and route planning between two points. It covers step-by-step implementation of core APIs, including Google Maps Android API v2 configuration, location services, Google Places API queries, map marker display, and path drawing. With code examples and best practices, it aims to help developers build robust and feature-rich mapping applications.

Introduction

Integrating mapping functionalities into mobile applications has become essential for enhancing user experience. Google Maps API offers a powerful toolkit for Android developers, supporting everything from basic map displays to advanced location-based services. This article systematically explains how to leverage Google Maps API in Android apps to achieve current location tracking, search for nearby places (such as police stations), and draw routes between points. Through detailed step-by-step analysis, we delve into the core features of the API and provide practical code examples to assist developers in creating efficient and reliable mapping applications.

Basic Configuration of Google Maps Android API v2

First, developers need to familiarize themselves with the integration process of Google Maps Android API v2. This involves creating a project in Google Cloud Console, enabling the Maps SDK for Android, generating an API key, and configuring permissions and metadata in the AndroidManifest.xml file of the Android project. For example, add the following permissions to access network and location services:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Additionally, include dependencies in the build.gradle file, such as com.google.android.gms:play-services-maps:18.0.0. After configuration, embed the map view in the layout file using MapFragment or SupportMapFragment. By initializing the GoogleMap object, developers can customize map types, controls, and interactive behaviors.

Obtaining Current Location

Implementing current location tracking is a core functionality of mapping applications. Android provides multiple methods for retrieving device location, with the Fused Location Provider API from Google Play Services recommended due to its combination of GPS, Wi-Fi, and cellular data for high accuracy and low power consumption. First, check location permissions to ensure the app has user authorization. Then, create an instance of FusedLocationProviderClient and request location updates. Here is a simplified code example:

FusedLocationProviderClient fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
    fusedLocationClient.getLastLocation()
        .addOnSuccessListener(this, location -> {
            if (location != null) {
                double latitude = location.getLatitude();
                double longitude = location.getLongitude();
                // Mark current location on the map
                LatLng currentLatLng = new LatLng(latitude, longitude);
                mMap.addMarker(new MarkerOptions().position(currentLatLng).title("Current Location"));
                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLatLng, 15));
            }
        });
}

This code retrieves the last known location and adds a marker on the map. For real-time updates, use the requestLocationUpdates() method. Handle permission requests and scenarios where location is unavailable to enhance app robustness.

Searching for Nearby Places

After obtaining the current location, the next step is to search for nearby places, such as police stations. Google Places API offers rich interfaces for querying place information. First, enable the Places API in Google Cloud Console and obtain an API key. Using the Places SDK for Android, perform searches via FindCurrentPlaceRequest or FindAutocompletePredictionsRequest. The following example demonstrates how to search for nearby police stations based on latitude and longitude:

// Assume currentLatLng is a LatLng object for the current location
List<Place.Field> placeFields = Arrays.asList(Place.Field.NAME, Place.Field.LAT_LNG);
FindCurrentPlaceRequest request = FindCurrentPlaceRequest.newInstance(placeFields);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
    Task<FindCurrentPlaceResponse> placeResponse = placesClient.findCurrentPlace(request);
    placeResponse.addOnCompleteListener(task -> {
        if (task.isSuccessful()) {
            FindCurrentPlaceResponse response = task.getResult();
            for (PlaceLikelihood placeLikelihood : response.getPlaceLikelihoods()) {
                Place place = placeLikelihood.getPlace();
                if (place.getName() != null && place.getName().toLowerCase().contains("police")) {
                    // Mark nearby police station on the map
                    mMap.addMarker(new MarkerOptions()
                        .position(place.getLatLng())
                        .title(place.getName()));
                }
            }
        }
    });
}

This code uses PlacesClient to search for current places and filters those with names containing "police". Developers can adjust search parameters, such as radius or type, based on requirements. The Places API also supports autocomplete and detail queries to improve user experience.

Displaying Map Markers and Info Windows

Displaying markers and info windows on the map is key to visually presenting place information. Use the GoogleMap.addMarker() method to add markers, and customize icons, titles, and snippets via MarkerOptions. To enhance interactivity, implement InfoWindowAdapter to customize info window content. For example, create a custom adapter to show place names and distances:

mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
    @Override
    public View getInfoWindow(Marker marker) {
        return null; // Use default window
    }

    @Override
    public View getInfoContents(Marker marker) {
        View infoWindow = getLayoutInflater().inflate(R.layout.custom_info_window, null);
        TextView titleView = infoWindow.findViewById(R.id.title);
        TextView snippetView = infoWindow.findViewById(R.id.snippet);
        titleView.setText(marker.getTitle());
        snippetView.setText(marker.getSnippet());
        return infoWindow;
    }
});

By designing a custom layout file custom_info_window.xml, developers can create rich information display interfaces. This helps users quickly access place details and enhances the app's professionalism.

Drawing Routes Between Two Points

Route planning is another crucial functionality in mapping applications. Google Maps Directions API can be used to calculate routes between two points and draw them on the map. First, enable the Directions API and obtain a key. Then, use HTTP requests or the Places SDK's FetchRouteRequest to retrieve route data. The following example shows how to fetch a driving route via an HTTP request:

String origin = "latitude,longitude"; // Starting coordinates
String destination = "latitude,longitude"; // Destination coordinates
String url = "https://maps.googleapis.com/maps/api/directions/json?origin=" + origin + "&destination=" + destination + "&key=YOUR_API_KEY";

RequestQueue queue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
    response -> {
        try {
            JSONObject jsonResponse = new JSONObject(response);
            JSONArray routes = jsonResponse.getJSONArray("routes");
            if (routes.length() > 0) {
                JSONObject route = routes.getJSONObject(0);
                JSONObject overviewPolyline = route.getJSONObject("overview_polyline");
                String encodedPath = overviewPolyline.getString("points");
                List<LatLng> path = decodePoly(encodedPath); // Decode polyline
                mMap.addPolyline(new PolylineOptions().addAll(path).width(10).color(Color.BLUE));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }, error -> {
        // Handle error
    });
queue.add(stringRequest);

This code sends a GET request to the Directions API, parses the JSON response, extracts the polyline encoding, and decodes it into a LatLng list using a custom decodePoly method. Then, draw the path on the map with PolylineOptions. Developers can add markers for start and end points or integrate traffic information to optimize routes.

Best Practices and Optimization Tips

Following best practices during development can improve app performance and user experience. First, always check location permissions in the foreground and handle dynamic permission requests with ActivityCompat.requestPermissions. Second, optimize Places API usage by caching frequently queried results to reduce network requests—for example, using SharedPreferences to store recent search data. Additionally, consider battery life by setting appropriate update intervals and priorities with LocationRequest. For route drawing, implement offline support or fallback options for network-unavailable scenarios. Finally, test the app on different devices and Android versions to ensure functional stability.

Conclusion

This article systematically explains the process of implementing current location tracking, nearby place searches, and route planning in Android applications using Google Maps API. From basic configuration to advanced features, we have demonstrated how to integrate Google Maps Android API v2, retrieve location data, use Places API for place searches, customize map markers, and draw routes through code examples and step-by-step analysis. These techniques are not limited to specific scenarios like searching for police stations but can be extended to other place types and interactive needs. Developers should combine best practices to optimize performance and enhance user experience, building efficient and reliable mapping applications. As APIs evolve, it is recommended to follow Google's official documentation for the latest features and security guidelines.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.