En Android Studio
Crear un nuevo proyecto en Android Studio


De los archivos creados automáticamente por Android Studio, copiar del archivo “google_maps_api.xml” el “package name” que será utilizado para crear la API Key.
[xml]
<resources>
<!–
TODO: Before you run your application, you need a Google Maps API key.
To get one, follow this link, follow the directions and press "Create" at the end:
https://console.developers.google.com/flows/enableapi?apiid=maps_android_backend&keyType=CLIENT_SIDE_ANDROID&r=FA:00:84:52:F3:38:A0:71:A3:D7:C1:9D:4C:77:F9:2A:5E:2E:E1:B4%3Bcl.petertips.mapas
You can also add your credentials to an existing key, using these values:
Package name:
FA:00:84:52:F3:38:A0:71:A3:D7:C1:9D:4C:77:F9:2A:5E:2E:E1:BB
SHA-1 certificate fingerprint:
FA:00:84:52:F3:38:A0:71:A3:D7:C1:9D:4H:77:F9:2A:5E:2E:E1:B4
Alternatively, follow the directions here:
https://developers.google.com/maps/documentation/android/start#get-key
Once you have your key (it starts with "AIza"), replace the "google_maps_key"
string in this file.
–>
<string name="google_maps_key" templateMergeStrategy="preserve" translatable="false">YOUR_KEY_HERE</string>
</resources>
[/xml]
En Google API’s
Ahora deberás crear una API Key en google en el link https://console.developers.google.com, esta la utilizaremos mas adelante.

La API Key tiene un formato como este “BIzxSyCvE2EIzhqFUPxVYBNTxkJhxjMowXHbTJ7”
En el archivo “google_maps_api.xml”, cambiar la etiqueta string con el API Key generado anteriormente.
[xml]
<string name="google_maps_key" templatemergestrategy="preserve" translatable="false">YOUR_KEY_HERE</string>
[/xml]
En Android Studio
en Build.gradle, agregar “com.google.android.gms” como se muestra en el siguiente código:
[xml]
apply plugin: ‘com.android.application’
android {
compileSdkVersion 28
defaultConfig {
applicationId "cl.petertips.mapas"
minSdkVersion 15
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile(‘proguard-android-optimize.txt’), ‘proguard-rules.pro’
}
}
}
dependencies {
implementation fileTree(dir: ‘libs’, include: [‘*.jar’])
implementation ‘com.android.support:appcompat-v7:28.0.0’
implementation ‘com.google.android.gms:play-services-maps:16.1.0’
implementation "com.google.android.gms:play-services-location:16.0.0"
testImplementation ‘junit:junit:4.12’
androidTestImplementation ‘com.android.support.test:runner:1.0.2’
androidTestImplementation ‘com.android.support.test.espresso:espresso-core:3.0.2’
}
[/xml]
En la clase “MapsActivity” agregar “implements OnMapReadyCallback, LocationListener”
[java]
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener {
[/java]
Agregando los metodos “onLocationChanged, onStatusChanged, onProviderEnabled, onProviderDisabled”
[java]
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
[/java]
Agregar las propiedades:
[java]
private GoogleMap mMap;
double lt, ln;
[/java]
Agregar un nuevo metodo llamado “getLastKnownLocation”
[java]
private Location getLastKnownLocation(){
if( ActivityCompat.checkSelfPermission( this, Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission( this, Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED ){
return null;
}
LocationManager locationManager =
(LocationManager) this.getSystemService( LOCATION_SERVICE );
List<string> providers = locationManager.getProviders( true );
Location bestLocation = null;
for( String provider : providers ){
Location l = locationManager.getLastKnownLocation( provider );
if( l == null ){
continue;
}
if( bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy() ){
bestLocation = l; // Found best last known location;
}
}
return bestLocation;
}
[/java]
Modificar el método “onMapReady” por el siguiente código:
[java]
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setCompassEnabled(true);
/*// AGREGAR línea poligonal
PolylineOptions rectOptions = new PolylineOptions()
.add(new LatLng(37.35, -122.0))
.add(new LatLng(37.45, -122.0))
.add(new LatLng(37.45, -122.2))
.add(new LatLng(37.35, -122.2))
.add(new LatLng(37.35, -122.0));
Polyline polyline = mMap.addPolyline(rectOptions);
// AGREGAR polígono
Polygon polygon = mMap.addPolygon(new PolygonOptions()
.add(new LatLng(0, 0), new LatLng(0, 5), new LatLng(3, 5), new LatLng(0, 0))
.strokeColor(Color.RED)
.fillColor(Color.BLUE));*/
Location x = getLastKnownLocation();
lt=x.getLatitude();
ln=x.getLongitude();
// Instantiates a new CircleOptions object and defines the center and radius
Circle circle = mMap.addCircle(new CircleOptions()
.center(new LatLng(lt, ln))
.radius(1000)
.strokeColor(Color.RED)
.fillColor(Color.TRANSPARENT));
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(lt, ln);
mMap.addMarker(new MarkerOptions().position(sydney).title("Yo"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
[/java]
Acá deje comentado las opciones para crear Polígonos o Líneas polígonales. Podrían servir en algún momento.
Modificar el método “onLocationChanged” por el siguiente código:
[java]
@Override
public void onLocationChanged(Location location) {
Location x = getLastKnownLocation();
lt=x.getLatitude();
ln=x.getLongitude();
}
[/java]
Modificar el archivo “AndoridManifest.xml” para permitir el accesos a la aplicación de los diferentes Hardware del dispositivo.
[xml]
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
[/xml]
Así quedaría todo el código de “MapsActivity.java”
[java]
package cl.petertips.mapas;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
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.Circle;
import com.google.android.gms.maps.model.CircleOptions;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polygon;
import com.google.android.gms.maps.model.PolygonOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import java.util.List;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener {
private GoogleMap mMap;
double lt, ln;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@SuppressLint("MissingPermission")
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setCompassEnabled(true);
/*// AGREGAR línea poligonal
PolylineOptions rectOptions = new PolylineOptions()
.add(new LatLng(37.35, -122.0))
.add(new LatLng(37.45, -122.0))
.add(new LatLng(37.45, -122.2))
.add(new LatLng(37.35, -122.2))
.add(new LatLng(37.35, -122.0));
Polyline polyline = mMap.addPolyline(rectOptions);
// AGREGAR polígono
Polygon polygon = mMap.addPolygon(new PolygonOptions()
.add(new LatLng(0, 0), new LatLng(0, 5), new LatLng(3, 5), new LatLng(0, 0))
.strokeColor(Color.RED)
.fillColor(Color.BLUE));*/
Location x = getLastKnownLocation();
lt=x.getLatitude();
ln=x.getLongitude();
// Instantiates a new CircleOptions object and defines the center and radius
Circle circle = mMap.addCircle(new CircleOptions()
.center(new LatLng(lt, ln))
.radius(1000)
.strokeColor(Color.RED)
.fillColor(Color.TRANSPARENT));
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(lt, ln);
mMap.addMarker(new MarkerOptions().position(sydney).title("Yo"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
private Location getLastKnownLocation(){
if( ActivityCompat.checkSelfPermission( this, Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission( this, Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED ){
return null;
}
LocationManager locationManager =
(LocationManager) this.getSystemService( LOCATION_SERVICE );
List<String> providers = locationManager.getProviders( true );
Location bestLocation = null;
for( String provider : providers ){
Location l = locationManager.getLastKnownLocation( provider );
if( l == null ){
continue;
}
if( bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy() ){
bestLocation = l; // Found best last known location;
}
}
return bestLocation;
}
@Override
public void onLocationChanged(Location location) {
Location x = getLastKnownLocation();
lt=x.getLatitude();
ln=x.getLongitude();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
}
[/java]