The goal of this tutorial is to learn how to integrate google maps into your application.
- android studio project
- google cloud platform account
Create a new empty project you can give it any name make sure that the lowest api level is >= 14. now we're going to include the necessary libraries.
-
- Start Android Studio.
- On the Tools menu, click Android > SDK Manager.
- Update the Android Studio SDK Manager: click SDK Tools, expand Support Repository, select Google Repository, and then click OK.
apply plugin: 'com.android.application'
...
dependencies {
compile 'com.google.android.gms:play-services-maps:10.2.1'
}
To get an api key you should have to create a google cloud platform account, you can follow the instructions here. you can afford to skip step 5 and 6 since this is just for the lab.
if you don't want to set up an account now here's a free key you can use
AIzaSyCkPm6lUfs1i3qcPS1_EupwRoD25HHNBpk
Follow the steps below to include the API key in your application's manifest, contained in the file AndroidManifest.xml.
- In AndroidManifest.xml, add the following element as a child of the
<application>
element, by inserting it just before the closing</application>
tag:
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="YOUR_API_KEY"/>
-
Substitute your
API key
forYOUR_API_KEY
in the value attribute. This element sets the keycom.google.android.geo.API_KEY
to the value of yourAPI key
. -
Save AndroidManifest.xml and re-build your application.
What we want to be able to do is display a map showing the current location of the user.
include the SupportMapFragment in your main activity fragment file
<fragment
android:id="@+id/map_fragment"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
we're going to get a refrence to the fragment and set some markers with it
in your onCreate method you need to Obtain the SupportMapFragment and get notified when the map is ready to be used
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map_fragment);
mapFragment.getMapAsync(this);
we need to implement the OnMapReadyCallback
so add this to the end of your class and @Override
the onMapReady
method
public class MainActivity extends FragmentActivity implements OnMapReadyCallback{
...
@Override
public void onMapReady(GoogleMap googleMap) {
//Add the marker logic here
}
...
}
Now we can set a marker based on the longitude and latitude
mMap = googleMap;
// Add a marker in 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));