Sat. Dec 21st, 2024

To create a Google Map in an Android application and display specific locations using latitude and longitude, follow these steps:


1. Set Up the Project

  1. Open Android Studio and create a new project with the Google Maps Activity template.
  2. Add the necessary Google Maps dependency (this is typically pre-included in the template):
   implementation 'com.google.android.gms:play-services-maps:18.1.0'

2. Get a Google Maps API Key

  1. Go to the Google Cloud Console.
  2. Enable the Maps SDK for Android API for your project.
  3. Generate an API key and add it to your AndroidManifest.xml:
   <meta-data
       android:name="com.google.android.geo.API_KEY"
       android:value="YOUR_API_KEY_HERE" />

3. Modify the Activity Code

Update the MapsActivity.kt file to include custom markers for specific locations.

Imports

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

Activity Code

class MapsActivity : AppCompatActivity(), OnMapReadyCallback {

    private lateinit var mMap: GoogleMap

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_maps)

        // Obtain the SupportMapFragment and get notified when the map is ready to be used
        val mapFragment = supportFragmentManager
            .findFragmentById(R.id.map) as SupportMapFragment
        mapFragment.getMapAsync(this)
    }

    override fun onMapReady(googleMap: GoogleMap) {
        mMap = googleMap

        // Add markers for specific locations
        val location1 = LatLng(37.7749, -122.4194) // San Francisco
        val location2 = LatLng(34.0522, -118.2437) // Los Angeles
        val location3 = LatLng(40.7128, -74.0060)  // New York

        mMap.addMarker(MarkerOptions().position(location1).title("San Francisco"))
        mMap.addMarker(MarkerOptions().position(location2).title("Los Angeles"))
        mMap.addMarker(MarkerOptions().position(location3).title("New York"))

        // Move the camera to the first location
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(location1, 5f))
    }
}

4. Update the XML Layout

Ensure the activity_maps.xml file contains a SupportMapFragment:

<fragment
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

5. Test the Application

  1. Build and run the application on a device or an emulator.
  2. The map should display markers for the specific locations provided (e.g., San Francisco, Los Angeles, and New York).

Optional Customizations

  • Change Marker Icons:
   val customIcon = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)
   mMap.addMarker(MarkerOptions().position(location1).title("San Francisco").icon(customIcon))
  • Add Click Listeners for Markers:
   mMap.setOnMarkerClickListener { marker ->
       Toast.makeText(this, "Clicked: ${marker.title}", Toast.LENGTH_SHORT).show()
       true
   }
  • Set Different Zoom Levels:
   mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(location1, 10f)) // Closer view

By Rajashekar

I’m (Rajashekar) a core Android developer with complimenting skills as a web developer from India. I cherish taking up complex problems and turning them into beautiful interfaces. My love for decrypting the logic and structure of coding keeps me pushing towards writing elegant and proficient code, whether it is Android, PHP, Flutter or any other platforms. You would find me involved in cuisines, reading, travelling during my leisure hours.

Leave a Reply

Your email address will not be published. Required fields are marked *