I've been coding an app that uses the gps sensor to get your location and centers the map around you, I have been using the funcion :
final LocationListener locationListenerFunc = new LocationListener()
but it's not working for me, I have been going for hours but i still don't see the text changes (and i change it when you go into the onLocationChanged method,
I'm doing everything by the example.
here is my code >
what's the problem ?
package greenroadproject.greenroadproject2;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.text.format.Time;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
private Button startTrackingButton;
private Button stopTrackingButton;
private TextView mainText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_fragment_layout);
//GPS LOCATION MANAGER
final LocationManager manager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
final LocationListener locationListenerFunc = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
/// HERE IS MY PROBLEM HE DOESN'T GO IN HERE
/// HERE IS MY PROBLEM HE DOESN'T GO IN HERE
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location.getLongitude()), 13));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(location.getLatitude(), location.getLongitude())) // Sets the center of the map to location user
.zoom(17) // Sets the zoom
.bearing(90) // Sets the orientation of the camera to east
.tilt(30) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
Time today = new Time(Time.getCurrentTimezone());
today.setToNow();
mainText.setText("gotNew Location at: "+today.format("%k:%M:%S"));
///
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
//casting to button
startTrackingButton = (Button) findViewById(R.id.BTStartTracking);
stopTrackingButton = (Button) findViewById(R.id.BTStopTracking);
mainText = (TextView) findViewById(R.id.TVMainTextView);
//setting up map
setUpMapIfNeeded();
//start tracking button touch listener
stopTrackingButton.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
//Do stuff here
centerMapOnMyLocation(); //centers the map on user location
mainText.setText("user location enabled");
}
});
//stop tracking button touch listener
startTrackingButton.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
//Do stuff here
Time today = new Time(Time.getCurrentTimezone());
today.setToNow();
mainText.setText("first time is: "+today.format("%k:%M:%S"));
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
3000, 0, locationListenerFunc);
}
});
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
/**
* Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
* installed) and the map has not already been instantiated.. This will ensure that we only ever
* call {#link #setUpMap()} once when {#link #mMap} is not null.
* <p/>
* If it isn't installed {#link SupportMapFragment} (and
* {#link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
* install/update the Google Play services APK on their device.
* <p/>
* A user can return to this FragmentActivity after following the prompt and correctly
* installing/updating/enabling the Google Play services. Since the FragmentActivity may not
* have been completely destroyed during this process (it is likely that it would only be
* stopped or paused), {#link #onCreate(Bundle)} may not be called again so we should call this
* method in {#link #onResume()} to guarantee that it will be called.
*/
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
//setUpMap();
centerMapOnMyLocation(); //centers the map on user location
}
}
}
/**
* This is where we can add markers or lines, add listeners or move the camera. In this case, we
* just add a marker near Africa.
* <p/>
* This should only be called once and when we are sure that {#link #mMap} is not null.
*/
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
}
private void centerMapOnMyLocation() {
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
//sets text >
double Lad = location.getLatitude();
double Long = location.getLongitude();
mainText.setText("lat: "+ String.valueOf(Lad)+", "+ "long: " +String.valueOf(Long));
if (location != null)
{
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location.getLongitude()), 13));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(location.getLatitude(), location.getLongitude())) // Sets the center of the map to location user
.zoom(17) // Sets the zoom
.bearing(90) // Sets the orientation of the camera to east
.tilt(30) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
}
}
Change LocationManager.GPS_PROVIDER to LocationManager.NETWORK_PROVIDER
Related
I am working on a map application, using android studio.
I have a map activity and I need some buttons on my map, for example zoom in,zoom out,search,...
I want to hide these buttons after a while and show them again onClick.
but I don't know how to do that.
here is my code
MapActivity.java
package com.example.tourismproject;
import android.location.Location;
import android.content.IntentSender;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
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 FragmentActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
public static final String TAG = MapsActivity.class.getSimpleName();
/*
* Define a request code to send to Google Play services
* This code is returned in Activity.onActivityResult
*/
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private GoogleMap mMap; // Might be null if Google Play services APK is not available
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private float zoomLevel = 15; //street view
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1000); // 1 second, in milliseconds
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
mGoogleApiClient.connect();
}
#Override
protected void onPause() {
super.onPause();
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
/**
* Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
* installed) and the map has not already been instantiated.. This will ensure that we only ever
* call {#link #setUpMap()} once when {#link #mMap} is not null.
* <p/>
* If it isn't installed {#link SupportMapFragment} (and
* {#link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
* install/update the Google Play services APK on their device.
* <p/>
* A user can return to this FragmentActivity after following the prompt and correctly
* installing/updating/enabling the Google Play services. Since the FragmentActivity may not
* have been completely destroyed during this process (it is likely that it would only be
* stopped or paused), {#link #onCreate(Bundle)} may not be called again so we should call this
* method in {#link #onResume()} to guarantee that it will be called.
*/
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
/**
* This is where we can add markers or lines, add listeners or move the camera. In this case, we
* just add a marker near Africa.
* <p/>
* This should only be called once and when we are sure that {#link #mMap} is not null.
*/
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
}
private void handleNewLocation(Location location) {
Log.d(TAG, location.toString());
double currentLatitude = location.getLatitude();
double currentLongitude = location.getLongitude();
LatLng latLng = new LatLng(currentLatitude, currentLongitude);
//mMap.addMarker(new MarkerOptions().position(new LatLng(currentLatitude, currentLongitude)).title("Current Location"));
MarkerOptions options = new MarkerOptions()
.position(latLng)
.title("I am here!");
mMap.addMarker(options);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoomLevel));
}
#Override
public void onConnected(Bundle bundle) {
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
} else {
handleNewLocation(location);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
/*
* Google Play services can resolve some errors it detects.
* If the error has a resolution, try sending an Intent to
* start a Google Play services activity that can resolve
* error.
*/
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
} catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
} else {
/*
* If no resolution is available, display a dialog to the
* user with the error.
*/
Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
}
}
#Override
public void onLocationChanged(Location location) {
handleNewLocation(location);
}
}
and my XML file is :
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.tourismproject.MapsActivity" />
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//hide buttons after 1 sec
yourbutton.setVisibility(false);
}
}, 1000);
someView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(button.getVisibility()==View.VISIBLE){
button.setVisibility(View.GONE);
} else {
button.setVisibility(View.VISIBLE);
}
}
});
Also for better usability you can add some fading animation with something like this:
ObjectAnimator alpha = ObjectAnimator.ofFloat(button, "alpha", 1, 0);
//alpha.setDelay(500);
//alpha.setDuration(1000);
alpha.start();
You can use
#Override
public void onClick(View v) {
button.setVisibility(false);
}
you can use
Thread.sleep(3000);//for three seconds
button.setVisibility(false);
to make it invisible after a while //in this case after three seconds
i hope this is helpful
So for some reason when i try adding a marker to a geopoint, the marker fails to show up at the given location. I tried researching what could be the problem but for some reason my code seems to follow everything that i researched on. Can someone guide me in the right direction?
import android.content.Context;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.text.DecimalFormat;
public class MapsActivity extends FragmentActivity {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
/**
* Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
* installed) and the map has not already been instantiated.. This will ensure that we only ever
* call {#link #setUpMap()} once when {#link #mMap} is not null.
* <p/>
* If it isn't installed {#link SupportMapFragment} (and
* {#link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
* install/update the Google Play services APK on their device.
* <p/>
* A user can return to this FragmentActivity after following the prompt and correctly
* installing/updating/enabling the Google Play services. Since the FragmentActivity may not
* have been completely destroyed during this process (it is likely that it would only be
* stopped or paused), {#link #onCreate(Bundle)} may not be called again so we should call this
* method in {#link #onResume()} to guarantee that it will be called.
*/
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
/**
* This is where we can add markers or lines, add listeners or move the camera. In this case, we
* just add a marker near Africa.
* <p/>
* This should only be called once and when we are sure that {#link #mMap} is not null.
*/
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker").snippet("Snippet"));
// Enable MyLocation Layer of Google Map
mMap.setMyLocationEnabled(true);
// Get LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Create a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Get the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Get Current Location
Location myLocation = locationManager.getLastKnownLocation(provider);
// set map type
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// Get latitude of the current location
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
double longitude = location.getLongitude();
double latitude = location.getLatitude();
// Get longitude of the current location
// Create a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
// Show the current location in Google Map
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
//LatLng myCoordinates = new LatLng(latitude, longitude);
//CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(myCoordinates, 20);
//mMap.animateCamera(yourLocation);
mMap.animateCamera(CameraUpdateFactory.zoomTo(20));
mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("You are here!").snippet("Consider yourself located"));
LatLng toLatLng = new LatLng(40.6937, 73.9859);
mMap.addMarker(new MarkerOptions().position( new LatLng(40.6937, 73.9859)).title("You location is here!").snippet("Consider it located"));
}
}
public void onFinish() {
// Your code here to do something after the Map is rendered
}
}
The main issue you mention:
the marker fails to show up at the given location
It looks like the main reason is that the getLastKnownLocation() is returning null, so it never gets into your code which sets the Marker at the current position.
Instead of calling that method, you can set up a location listener, which will explicitly request a new location.
I cleaned up your code a bit, and got it working. Note that I removed the use of getLastKnownLocation(), and moved the logic you had in there to the onLocationChanged() callback.
I also added functionality to remove the previous "current location" Marker, and add a new one every time the location changes.
Also note that the one Marker showing up at the equator near Africa was due to this line, so I just commented that out:
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker").snippet("Snippet"));
Here is the full updated class code:
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
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.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import android.location.Criteria;
public class MapsActivity extends FragmentActivity implements LocationListener {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
LocationManager locationManager;
Marker marker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
#Override
protected void onPause() {
super.onPause();
//remove location listener
if (locationManager != null){
locationManager.removeUpdates(this);
}
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
//This was the Marker at equator near Africa
//mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker").snippet("Snippet"));
// Enable MyLocation Layer of Google Map
mMap.setMyLocationEnabled(true);
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
mMap.getUiSettings().setCompassEnabled(true);
mMap.getUiSettings().setRotateGesturesEnabled(true);
mMap.getUiSettings().setZoomGesturesEnabled(true);
// Get LocationManager object from System Service LOCATION_SERVICE
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, this);
}
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
}
}
public void onFinish() {
// Your code here to do something after the Map is rendered
}
#Override
public void onLocationChanged(Location location) {
double longitude = location.getLongitude();
double latitude = location.getLatitude();
// Create a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
// Show the current location in Google Map
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
if (marker != null) {
marker.remove();
}
marker = mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude))
.title("You are here!").snippet("Consider yourself located")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA)));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
Result:
Edit:
You picked an interesting spot to put your hard-coded Marker.
I replaced the marker code with this:
LatLng toLatLng = new LatLng(40.6937, 73.9859);
// Create a LatLng object for the current location
LatLng latLng = new LatLng(40.6937, 73.9859);
// Show the current location in Google Map
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
if (marker != null) {
marker.remove();
}
marker = mMap.addMarker(new MarkerOptions().position(new LatLng(40.6937, 73.9859))
.title("You are here!").snippet("Consider yourself located")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA)));
And it placed the marker at the given location. Note that there is some strange effect going on due to different satellite images.
Initial result:
Zoomed out to see where we are!
I'm developing an android app that can trace the users locations and movements, using GPS and draw and save a line or the tracks that can be sent to a receiver who can open and see the saved tracks on Google map.
I already have a working code that can send the location but the receiver can only see the single position where the user sent from with a marker.
But I want it to track the movement and send so that the receiver can see all the places the user went when the app was on.
I would be really grateful if anyone can help me with this.
This is the code, #Ranjith or if anyone can help me detect the problem here. My tracks/lines are still not drawing
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.Projection;
import com.google.android.gms.maps.StreetViewPanorama;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
public class MapsActivity extends FragmentActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener,
GoogleMap.OnMyLocationButtonClickListener,
OnMapReadyCallback {
/**
* The desired interval for location updates. Inexact. Updates may be more or less frequent.
*/
public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000;
/**
* The fastest rate for active location updates. Exact. Updates will never be more frequent
* than this value.
*/
public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS =
UPDATE_INTERVAL_IN_MILLISECONDS / 2;
// Keys for storing activity state in the Bundle.
protected final static String REQUESTING_LOCATION_UPDATES_KEY = "requesting-location-updates-key";
protected final static String LOCATION_KEY = "location-key";
protected final static String LAST_UPDATED_TIME_STRING_KEY = "last-updated-time-string-key";
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
private GoogleApiClient mGoogleApiClient;
private Location mCurrentLocation;
/**
* Tracks the status of the location updates request. Value changes when the user presses the
* Start Updates and Stop Updates buttons.
*/
protected Boolean mRequestingLocationUpdates;
protected Button mStartUpdatesButton;
protected Button mStopUpdatesButton;
protected Button mSendPositionButton;
protected TextView mLastUpdateTimeTextView;
protected TextView mLatitudeTextView;
protected TextView mLongitudeTextView;
/**
* Stores parameters for requests to the FusedLocationProviderApi.
*/
protected LocationRequest mLocationRequest;
/**
* Time when the location was updated represented as a String.
*/
protected String mLastUpdateTime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Locate the UI widgets.
mStartUpdatesButton = (Button) findViewById(R.id.start_updates_button);
mStopUpdatesButton = (Button) findViewById(R.id.stop_updates_button);
mSendPositionButton = (Button) findViewById(R.id.send_position_button);
mLatitudeTextView = (TextView) findViewById(R.id.latitude_text);
mLongitudeTextView = (TextView) findViewById(R.id.longitude_text);
mLastUpdateTimeTextView = (TextView) findViewById(R.id.last_update_time_text);
mRequestingLocationUpdates = false;
mLastUpdateTime = "";
SupportMapFragment mapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
mMap = mapFragment.getMap();
// Update values using data stored in the Bundle.
updateValuesFromBundle(savedInstanceState);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
createLocationRequest();
}
#Override
protected void onResume() {
super.onResume();
mGoogleApiClient.connect();
}
#Override
public void onPause() {
super.onPause();
mGoogleApiClient.disconnect();
}
#Override
public void onMapReady(GoogleMap map) {
map.setMyLocationEnabled(true);
map.setOnMyLocationButtonClickListener(this);
}
/**
* Implementation of {#link LocationListener}.
*/
#Override
public void onLocationChanged(Location location) {
/**
if (location.distanceTo(mCurrentLocation) > 10)
mMap.addMarker(new MarkerOptions().position(new LatLng(location.getLatitude(),
location.getLongitude())).title("Marker"));
mCurrentLocation = location;
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
updateUI();
Toast.makeText(this, getResources().getString(R.string.location_updated_message),
Toast.LENGTH_SHORT).show();
*/
}
public void handleGetDirectionsResult(ArrayList<LatLng> directionPoints) {
PolylineOptions rectLine = new PolylineOptions().width(15).color(Color.RED);
Polyline routePolyline = null;
for (int i = 0; i < directionPoints.size(); i++) {
rectLine.add(directionPoints.get(i));
}
if (routePolyline != null){
routePolyline.remove();
}
routePolyline = mMap.addPolyline(rectLine);
}
#Override
public void onConnected(Bundle connectionHint) {
if (mCurrentLocation == null) {
mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
}
updateUI();
}
#Override
public void onConnectionSuspended(int cause) {
// Do nothing
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// Do nothing
}
#Override
public boolean onMyLocationButtonClick() {
Toast.makeText(this, mCurrentLocation.toString(), Toast.LENGTH_SHORT).show();
// Return false so that we don't consume the event and the default behavior still occurs
// (the camera animates to the user's current position).
return false;
}
/**
* Sets up the location request. Android has two location request settings:
* {#code ACCESS_COARSE_LOCATION} and {#code ACCESS_FINE_LOCATION}. These settings control
* the accuracy of the current location. This sample uses ACCESS_FINE_LOCATION, as defined in
* the AndroidManifest.xml.
* <p/>
* When the ACCESS_FINE_LOCATION setting is specified, combined with a fast update
* interval (5 seconds), the Fused Location Provider API returns location updates that are
* accurate to within a few feet.
* <p/>
* These settings are appropriate for mapping applications that show real-time location
* updates.
*/
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
// Sets the desired interval for active location updates. This interval is
// inexact. You may not receive updates at all if no location sources are available, or
// you may receive them slower than requested. You may also receive updates faster than
// requested if other applications are requesting location at a faster interval.
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
// Sets the fastest rate for active location updates. This interval is exact, and your
// application will never receive updates faster than this value.
mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
public void sendPositionButtonHandler(View view)
{
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "http://maps.google.com/?q=" +
mCurrentLocation.getLatitude() + "," + mCurrentLocation.getLongitude());
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.send_to)));
}
/**
* Handles the Start Updates button and requests start of location updates. Does nothing if
* updates have already been requested.
*/
public void startUpdatesButtonHandler(View view) {
if (!mRequestingLocationUpdates) {
mRequestingLocationUpdates = true;
setButtonsEnabledState();
startLocationUpdates();
}
}
/**
* Handles the Stop Updates button, and requests removal of location updates. Does nothing if
* updates were not previously requested.
*/
public void stopUpdatesButtonHandler(View view) {
if (mRequestingLocationUpdates) {
mRequestingLocationUpdates = false;
setButtonsEnabledState();
stopLocationUpdates();
}
}
/**
* Ensures that only one button is enabled at any time. The Start Updates button is enabled
* if the user is not requesting location updates. The Stop Updates button is enabled if the
* user is requesting location updates.
*/
private void setButtonsEnabledState() {
if (mRequestingLocationUpdates) {
mStartUpdatesButton.setEnabled(false);
mStopUpdatesButton.setEnabled(true);
} else {
mStartUpdatesButton.setEnabled(true);
mStopUpdatesButton.setEnabled(false);
}
}
/**
* Requests location updates from the FusedLocationApi.
*/
protected void startLocationUpdates() {
// The final argument to {#code requestLocationUpdates()} is a LocationListener
// (http://developer.android.com/reference/com/google/android/gms/location/LocationListener.html).
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
/**
* Removes location updates from the FusedLocationApi.
*/
protected void stopLocationUpdates() {
// It is a good practice to remove location requests when the activity is in a paused or
// stopped state. Doing so helps battery performance and is especially
// recommended in applications that request frequent location updates.
// The final argument to {#code requestLocationUpdates()} is a LocationListener
// (http://developer.android.com/reference/com/google/android/gms/location/LocationListener.html).
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
/**
* Updates the latitude, the longitude, and the last location time in the UI.
*/
private void updateUI() {
if (mCurrentLocation != null) {
mLatitudeTextView.setText(String.valueOf(mCurrentLocation.getLatitude()));
mLongitudeTextView.setText(String.valueOf(mCurrentLocation.getLongitude()));
mLastUpdateTimeTextView.setText(mLastUpdateTime);
mMap.addMarker(new MarkerOptions().position(new LatLng(mCurrentLocation.getLatitude(),
mCurrentLocation.getLongitude())).title("Marker"));
}
}
/**
* Updates fields based on data stored in the bundle.
*
* #param savedInstanceState The activity state saved in the Bundle.
*/
private void updateValuesFromBundle(Bundle savedInstanceState) {
if (savedInstanceState != null) {
// Update the value of mRequestingLocationUpdates from the Bundle, and make sure that
// the Start Updates and Stop Updates buttons are correctly enabled or disabled.
if (savedInstanceState.keySet().contains(REQUESTING_LOCATION_UPDATES_KEY)) {
mRequestingLocationUpdates = savedInstanceState.getBoolean(
REQUESTING_LOCATION_UPDATES_KEY);
setButtonsEnabledState();
}
// Update the value of mCurrentLocation from the Bundle and update the UI to show the
// correct latitude and longitude.
if (savedInstanceState.keySet().contains(LOCATION_KEY)) {
// Since LOCATION_KEY was found in the Bundle, we can be sure that mCurrentLocation
// is not null.
mCurrentLocation = savedInstanceState.getParcelable(LOCATION_KEY);
}
// Update the value of mLastUpdateTime from the Bundle and update the UI.
if (savedInstanceState.keySet().contains(LAST_UPDATED_TIME_STRING_KEY)) {
mLastUpdateTime = savedInstanceState.getString(LAST_UPDATED_TIME_STRING_KEY);
}
updateUI();
}
}
}
Refer the PolylineOptions in developer document,
https://developers.google.com/android/reference/com/google/android/gms/maps/model/PolylineOptions
Here is sample code,
If you pass the list of LatLng values, you can draw a line on the map.
public void handleGetDirectionsResult(ArrayList<LatLng> directionPoints) {
PolylineOptions rectLine = new PolylineOptions().width(15).color(Color.RED); //red color line & size=15
Polyline routePolyline;
for (int i = 0; i < directionPoints.size(); i++) {
rectLine.add(directionPoints.get(i));
}
//clear the old line
if (routePolyline != null) {
routePolyline.remove();
}
// mMap is the Map Object
routePolyline = mMap.addPolyline(rectLine);
}
I am building an app to track a users training session ie running.
The app should record the users location and then create a polyline from the results.
I have used the navigation drawer activity within android studio to strucure my app. However I think this has put my map fragment within a fragment.
My problem is that I do not seem to be able to set defaults for the map. For example if I try to set the map type within the setUpMap to satelite the changes never take effect. This is not limited to setting default, I am also not getting location updates.
Any help would be greatly appreciated
Here is how my map is called:
package com.example.craig.runtrackerv3;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class menu1_fragment extends Fragment {
View rootview;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
rootview = inflater.inflate(R.layout.activity_maps, container, false);
return rootview;
}
}
Here is the map object:
package com.example.craig.runtrackerv3;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
/**
* Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
* installed) and the map has not already been instantiated.. This will ensure that we only ever
* call {#link #setUpMap()} once when {#link #mMap} is not null.
* <p/>
* If it isn't installed {#link SupportMapFragment} (and
* {#link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
* install/update the Google Play services APK on their device.
* <p/>
* A user can return to this FragmentActivity after following the prompt and correctly
* installing/updating/enabling the Google Play services. Since the FragmentActivity may not
* have been completely destroyed during this process (it is likely that it would only be
* stopped or paused), {#link #onCreate(Bundle)} may not be called again so we should call this
* method in {#link #onResume()} to guarantee that it will be called.
*/
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
/**
* This is where we can add markers or lines, add listeners or move the camera. In this case, we
* just add a marker near Africa.
* <p/>
* This should only be called once and when we are sure that {#link #mMap} is not null.
*/
private void setUpMap() {
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
String provider = locationManager.getBestProvider(criteria, true);
LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
showCurrentLocation(location);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
locationManager.requestLocationUpdates(provider, 2000, 0, locationListener);
// Getting initial Location
Location location = locationManager.getLastKnownLocation(provider);
// Show the initial location
if(location != null)
{
showCurrentLocation(location);
}
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
}
private void showCurrentLocation(Location location){
mMap.clear();
LatLng currentPosition = new LatLng(location.getLatitude(),location.getLongitude());
mMap.addMarker(new MarkerOptions()
.position(currentPosition)
.snippet("Lat: " + location.getLatitude() + ", Lng: " + location.getLongitude())
//.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_peterleow))
.flat(true)
.title("I'm here!"));
// Zoom in, animating the camera.
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentPosition, 18));
}
}
Here is the map xml:
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:id="#+id/map"
tools:context="com.example.craig.runtrackerv3.MapsActivity"
android:name="com.google.android.gms.maps.SupportMapFragment" />
My suspicion is I need some sort of callback but I'm not to sure how to implement it.
Any help would be greatly appreciated.
You need to use Map Fragment instead of Map Activity.
public class MapaFragment extends Fragment implements OnMapClickListener {
MapView mapView;
GoogleMap map;
.....
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_map, container, false);
MapsInitializer.initialize(getActivity());
mapView = (MapView) v.findViewById(R.id.mapaPrincipal);
mapView.onCreate(savedInstanceState);
map = mapView.getMap();
if(map != null) {
map.setOnMapClickListener(this);
}
return v;
}
}
You just don't init map correctly, it tight connect to activity life cycle
GoogleMap mMap;
MapView map = (MapView) findViewById(R.id.map);
map.onCreate(mActivity.getStateBundle());
map.onResume();
map.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
initializeMap(googleMap, device);
}
});
and when you done with all call
map.onPause();
map.onDestroy();
I'm new to android development and I had been trying to display a map in my application for some time now. I finally managed to do it but I want to display it with some specified options such as zoom level, location, etc but its proving difficult.
The following is my .xml file
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment"/>
And the following is my .java file
package com.fourapps.cabkonnect;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import android.location.Location;
import android.graphics.Color;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
/**
* Created by nanakay on 6/6/13.
*/
public class Home extends FragmentActivity {
GoogleMap map;
private static final LatLng GOLDEN_GATE_BRIDGE = new LatLng(37.828891,-122.485884);
private static final LatLng APPLE = new LatLng(37.3325004578, -122.03099823);
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
if (map == null) {
Toast.makeText(this, "Google maps not available", Toast.LENGTH_LONG).show();
}
}
}
The map is displaying but I would want to display it with my own options.
I would be very happy if someone could help. Thanks
First have to obtain the current location:
private Location mCurrentLocation;
mCurrentLocation = mLocationClient.getLastLocation();
Read here to know more.
And then you can animate to the location using:
LatLng myLaLn = new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());
CameraPosition camPos = new CameraPosition.Builder().target(myLaLn)
.zoom(15)
.bearing(45)
.tilt(70)
.build();
CameraUpdate camUpd3 = CameraUpdateFactory.newCameraPosition(camPos);
map.animateCamera(camUpd3);
I give you a simple but complete example to show a map and the current location:
public class MainActivity extends FragmentActivity implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener {
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private LocationClient mLocationClient;
private Location mCurrentLocation;
private GoogleMap map;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
setUpLocationClientIfNeeded();
mLocationClient.connect();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the
// map.
if (map == null) {
// Try to obtain the map from the SupportMapFragment.
map = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
// Check if we were successful in obtaining the map.
if (map == null) {
Toast.makeText(this, "Google maps not available",
Toast.LENGTH_LONG).show();
}
}
}
private void setUpLocationClientIfNeeded() {
if (mLocationClient == null) {
Toast.makeText(getApplicationContext(), "Waiting for location",
Toast.LENGTH_SHORT).show();
mLocationClient = new LocationClient(getApplicationContext(), this, // ConnectionCallbacks
this); // OnConnectionFailedListener
}
}
#Override
public void onPause() {
super.onPause();
if (mLocationClient != null) {
mLocationClient.disconnect();
}
}
/*
* Called by Location Services when the request to connect the client
* finishes successfully. At this point, you can request the current
* location or start periodic updates
*/
#Override
public void onConnected(Bundle dataBundle) {
mCurrentLocation = mLocationClient.getLastLocation();
if (mCurrentLocation != null) {
Toast.makeText(getApplicationContext(), "Found!",
Toast.LENGTH_SHORT).show();
centerInLoc();
}
}
private void centerInLoc() {
LatLng myLaLn = new LatLng(mCurrentLocation.getLatitude(),
mCurrentLocation.getLongitude());
CameraPosition camPos = new CameraPosition.Builder().target(myLaLn)
.zoom(15).bearing(45).tilt(70).build();
CameraUpdate camUpd3 = CameraUpdateFactory.newCameraPosition(camPos);
map.animateCamera(camUpd3);
MarkerOptions markerOpts = new MarkerOptions().position(myLaLn).title(
"my Location");
map.addMarker(markerOpts);
}
/*
* Called by Location Services if the connection to the location client
* drops because of an error.
*/
#Override
public void onDisconnected() {
// Display the connection status
Toast.makeText(this, "Disconnected. Please re-connect.",
Toast.LENGTH_SHORT).show();
}
/*
* Called by Location Services if the attempt to Location Services fails.
*/
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
/*
* Google Play services can resolve some errors it detects. If the error
* has a resolution, try sending an Intent to start a Google Play
* services activity that can resolve error.
*/
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(this,
CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
} catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
} else {
/*
* If no resolution is available
*/
Log.e("Home", Integer.toString(connectionResult.getErrorCode()));
}
}
}
Note1: I omitted the "Check for Google Play Services" part by simplicity but it should be added as a good practice.
Note2: You need the google-play-services_lib project and reference it from yours.
You can find all information about interacting with google maps in android here
From the google maps documentation referenced above, just some examples:
Zoom controls:
The Maps API provides built-in zoom controls that appear in the bottom right hand corner of the map. These are enabled by default, but can be disabled by calling UiSettings.setZoomControlsEnabled(boolean).
My Location button:
The My Location button appears in the top right corner of the screen only when the My Location layer is enabled. When a user clicks the button, the camera animates to focus on the user's current location if the user's location is currently known. A click will also trigger the GoogleMap.OnMyLocationButtonClickListener. You can disable the button from appearing altogether by calling UiSettings.setMyLocationButtonEnabled(boolean).
Add a marker:
The below example demonstrates how to add a marker to a map. The marker is created at coordinates 0,0, and displays the string "Hello world" in an infowindow when clicked.
private GoogleMap mMap;
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
mMap.addMarker(new MarkerOptions()
.position(new LatLng(0, 0))
.title("Hello world"));