ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Mobile Application Development 1
    COMP4124
    Progress0 / 33 topics
    Topics
    1. Mobiles Application Development Platform2. HTML5 for Mobiles3. Android OS: Architecture, Framework and Application Development4. iOS: Architecture, Framework5. Application Development with Windows Mobile6. Eclipse7. Fragments8. Calling Built-in Applications using Intents9. Displaying Notifications10. Components of a Screen11. Adapting to Display Orientation12. Managing Changes to Screen Orientation13. Utilizing the Action Bar14. Creating the User Interface15. Listening for UI Notifications16. Views17. User Preferences18. Persisting & Sharing Data19. Sending SMS Messages20. Getting Feedback21. Sending E-mail22. Displaying Maps23. Consuming Web Services Using HTTP24. Web Services: Accessing and Creating25. Threading26. Publishing Android Applications27. Deployment on App Stores28. Mobile Programming Languages29. Challenges with Mobility and Wireless Communication30. Location-aware Applications31. Performance/Power Tradeoffs32. Mobile Platform Constraints33. Emerging Technologies
    COMP4124›Displaying Maps
    Mobile Application Development 1Topic 22 of 33

    Displaying Maps

    6 minread
    1,043words
    Intermediatelevel

    Displaying Maps in Android

    Displaying maps in your Android app allows you to provide location-based services, such as showing points of interest, navigation, or user locations. Android provides several tools and libraries to easily integrate maps into your application. The most commonly used tool for displaying maps in Android is Google Maps API.

    Here’s a detailed explanation of how to integrate and display maps in your Android app:


    1. Google Maps API Overview

    Google Maps API allows you to embed Google Maps into your Android application. It provides various features such as displaying maps, adding markers, handling user interactions (zoom, pan, etc.), and showing routes.

    To use Google Maps in your Android app, you need to integrate the Google Maps SDK into your project.


    2. Setting Up Google Maps in Your Project

    Before you can display maps in your app, you need to follow a few setup steps:

    A. Create a Google Maps Project in Google Cloud Console

    1. Go to the Google Cloud Console.
    2. Create a new project or select an existing project.
    3. In the search bar, type "Maps" and select Maps SDK for Android.
    4. Enable the Maps SDK for Android API for your project.
    5. Create API credentials (an API key) to authenticate your app’s requests to Google Maps.
    6. Copy the API key; you will need it in your app.

    B. Add Google Play Services Dependency

    In your Android project, you need to include Google Play Services for Maps. Open your build.gradle file (app-level) and add the following dependency:

    dependencies {
        implementation 'com.google.android.gms:play-services-maps:17.0.1'  // or the latest version
    }
    

    Then sync your project.

    C. Update AndroidManifest.xml

    In your AndroidManifest.xml file, you need to add permissions for internet access and the required features for Google Maps:

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    
    <application
        ... >
        <!-- Add Google Maps API Key -->
        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="YOUR_API_KEY_HERE" />
    
        <activity
            android:name=".MapsActivity"
            android:label="@string/title_activity_maps"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    

    Make sure to replace YOUR_API_KEY_HERE with the API key you obtained from Google Cloud Console.


    3. Creating a Map Activity

    Once you've set up the dependencies and permissions, you can start creating a map in your app.

    A. Define the MapFragment or SupportMapFragment

    To display a map, you’ll use the SupportMapFragment class. This class helps manage the map view and integrates it with the lifecycle of the activity. Here’s how to do it:

    1. In your activity layout XML (activity_maps.xml), add the SupportMapFragment:
    <fragment
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    

    B. Initialize the Map in Your Activity

    In your activity (MapsActivity.java), you need to initialize the map and ensure it’s ready for interaction. You do this by implementing the OnMapReadyCallback interface, which provides a callback method that’s triggered once the map is ready to use.

    import android.os.Bundle;
    import com.google.android.gms.maps.CameraUpdateFactory;
    import com.google.android.gms.maps.GoogleMap;
    import com.google.android.gms.maps.OnMapReadyCallback;
    import com.google.android.gms.maps.SupportMapFragment;
    import com.google.android.gms.maps.model.LatLng;
    import com.google.android.gms.maps.model.MarkerOptions;
    
    public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {
    
        private GoogleMap mMap;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_maps);
    
            // Get the SupportMapFragment and request the map asynchronously
            SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.map);
            mapFragment.getMapAsync(this);  // Callback when map is ready
        }
    
        // This method is triggered when the map is ready
        @Override
        public void onMapReady(GoogleMap googleMap) {
            mMap = googleMap;
    
            // Add a marker at a specific location (e.g., Sydney) and move the camera
            LatLng sydney = new LatLng(-34, 151);
            mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
            mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    
            // Optionally, zoom in to a specific level
            mMap.animateCamera(CameraUpdateFactory.zoomTo(10));
        }
    }
    
    • getMapAsync(this): This is used to request the map asynchronously.
    • onMapReady(GoogleMap googleMap): This callback is triggered once the map is ready to be used.

    In this example, the map centers on Sydney (with latitude -34 and longitude 151), adds a marker, and animates the camera to zoom in.


    4. Working with Map Features

    Once the map is ready, you can use various features to customize the map and enhance user interactions:

    A. Adding Markers

    Markers are visual indicators that show specific locations on the map. You can add markers at various latitudes and longitudes.

    LatLng location = new LatLng(37.7749, -122.4194);  // San Francisco
    mMap.addMarker(new MarkerOptions().position(location).title("Marker in San Francisco"));
    

    B. Changing the Camera Position

    You can move the camera to a specific location or animate the camera for smooth transitions.

    LatLng location = new LatLng(40.7128, -74.0060);  // New York City
    mMap.moveCamera(CameraUpdateFactory.newLatLng(location));
    mMap.animateCamera(CameraUpdateFactory.zoomTo(12));  // Zoom to level 12
    

    C. Enabling User Location

    To show the user’s current location, enable location tracking:

    mMap.setMyLocationEnabled(true);
    

    Note: You must request location permissions (ACCESS_FINE_LOCATION) at runtime if you're targeting Android 6.0 (API level 23) or higher.


    5. Customizing Map Appearance

    You can customize the appearance of your map by applying a style to the map. Google Maps supports custom styling through a JSON format, which you can either load from a file or directly apply in your code.

    A. Applying a Custom Style

    Create a JSON file for the map style and load it:

    1. Place your style JSON file in the res/raw/ directory (e.g., res/raw/map_style.json).
    2. Apply the style programmatically:
    try {
        boolean success = mMap.setMapStyle(
                MapStyleOptions.loadRawResourceStyle(this, R.raw.map_style));
        if (!success) {
            Log.e("MapsActivity", "Style parsing failed.");
        }
    } catch (Resources.NotFoundException e) {
        Log.e("MapsActivity", "Can't find style. Error: ", e);
    }
    

    This allows you to apply a custom style to the map, such as changing the colors of roads, water, and other elements.


    6. Conclusion

    Displaying maps in Android is a powerful feature that can be used for many purposes, from simple location display to complex navigation and interactive location-based services. With the Google Maps API, you can easily integrate maps into your app, add markers, customize the map’s appearance, and track the user’s location.

    By following the setup steps, adding the required dependencies, and using the SupportMapFragment class, you can start displaying maps and interacting with them in your Android app.

    Previous topic 21
    Sending E-mail
    Next topic 23
    Consuming Web Services Using HTTP

    Past Papers

    Open this section to load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time6 min
      Word count1,043
      Code examples0
      DifficultyIntermediate