I found a solution . The map may not have been initialized yet, try getMap() in a later point of the lifecycle, like onResume()
My code is
protected void onResume() {
super.onResume();
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
if (resultCode == ConnectionResult.SUCCESS){
Toast.makeText(getApplicationContext(),
"isGooglePlayServicesAvailable SUCCESS",
Toast.LENGTH_LONG).show();
if(gMap == null){
gMap = mMapView.getMap();
if(gMap != null){
gMap.setMyLocationEnabled(true);
gMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
}else{
Toast.makeText(getApplicationContext(),
"cannot getMap!",
Toast.LENGTH_LONG).show();
}
}
}else{
GooglePlayServicesUtil.getErrorDialog(resultCode, this, RQS_GooglePlayServices);
}
}
Edited you have done below step:
Add Play Services Library in project :
Eclipse > import > Android > Existing Android code in to workspace
Browse you SDK path like ~/android-sdk-linux/extras/google/google_play_services
import that project in to workspace
add above library project in to your project. run in Android Device only not in Emulator
it is simple check below code:
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
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 MainActivity extends Activity {
private GoogleMap MAP;
#Override
protected void onCreate(Bundle arg0) {
// TODO Auto-generated method stub
//setTheme(R.style.Theme_Sherlock);
super.onCreate(arg0);
setContentView(R.layout.activity_main);
FragmentManager myFM = getSupportFragmentManager();
SupportMapFragment myMAPF = (SupportMapFragment) myFM
.findFragmentById(R.id.fragment1);
MAP = myMAPF.getMap();
MAP.setMyLocationEnabled(true);
MAP.setMapType(GoogleMap.MAP_TYPE_HYBRID);
MAP.setOnMapClickListener(new OnMapClickListener() {
#Override
public void onMapClick(LatLng point) {
// TODO Auto-generated method stub
MAP.addMarker(new MarkerOptions().position(point).title(
point.toString()));
}
});
}
}
more detail check this : clickhere & clickhere
as per your code check this:
Marker marker = map.add(new MarkerOptions()
.position(new LatLng(37.7750, 122.4183))
.title("San Francisco")
.snippet("Population: 776733"));
gMap.addMarker(marker);
Try this to add custom marker:
public void placingCurrentMarkerWithBalloon(String address)
{
LatLng current_latlng = new LatLng(cur_lat, cur_lng);
gMapview.addMarker(new MarkerOptions().position(current_latlng)
.title("Address")
.snippet(address)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.person_marker))
/*.icon(BitmapDescriptorFactory.defaultMarker())*/
).showInfoWindow();
}
Related
Instead of LocationManager, I have use LocationServices method to get current gps location and location updates.
this is the code:
public void onConnected(#Nullable Bundle bundle) {
mLocationRequest = new LocationRequest();//PRIORITY_BALANCED_POWER_ACCURACY
mLocationRequest.setInterval(1000*30*1);
mLocationRequest.setFastestInterval(1000*30*1);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest,this);
}
}
public void onLocationChanged(Location location) { mLastLocation = location;
if (mCurrLocationMarker != null)
{
mCurrLocationMarker.remove();
}
//Place current location marker
latLng = new LatLng(location.getLatitude(), location.getLongitude());
lat= location.getLatitude();
log=location.getLongitude();
trim_check_location_change(lat,log);
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(""+s);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
CurrentLocation = latLng;
}
As I move from from one place to another, blue marker moves accordingly.
however onlocationchanged method never gets called.
I've developed fused location api demo application and utility pack here.
General Utilities
Try it if useful for you. To get location using fused location api, you just have to write following snippet...
new LocationHandler(this)
.setLocationListener(new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// Get the best known location
}
}).start();
And if you want to customise it, simply find documentation here...
https://github.com/abhishek-tm/general-utilities-android/wiki/Location-Handler
Update
I've written a sample code according to your need, try this one...
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
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.Marker;
import in.teramatrix.utilities.service.LocationHandler;
import in.teramatrix.utilities.util.MapUtils;
/**
* Lets see how to use utilities module by implementing location listener.
*
* #author Khan
*/
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback, LocationListener {
private GoogleMap map;
private Marker marker;
private LocationHandler locationHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Obtaining an instance of map
FragmentManager manager = getSupportFragmentManager();
SupportMapFragment mapFragment = (SupportMapFragment) manager.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
this.locationHandler = new LocationHandler(this)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(5000)
.setFastestInterval(10000)
.setLocationListener(this);
}
#Override
public void onMapReady(GoogleMap map) {
this.map = map;
this.locationHandler.start();
}
#Override
public void onLocationChanged(Location location) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
if (marker == null) {
marker = MapUtils.addMarker(map, latLng, R.drawable.ic_current_location);
map.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 14), 500, null);
} else {
marker.setPosition(latLng);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (locationHandler != null) {
locationHandler.stop();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == LocationHandler.REQUEST_LOCATION) {
locationHandler.start();
}
}
}
Hope it will help you.
I am trying to implement Google Places Autocomplete API, but the search bar for it crashed on some phones every time when I search for something.
It does work on some phones (like Moto G 2nd Generation XT1068) but crashes on Lenovo A7000 whenever I search anything in the search bar and then press enter.
Another problem I face is; I want to change the default google maps location that shows near South Africa. Change it to a specific location. How can I do that?
package com.docto365.activity;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.ui.PlaceAutocompleteFragment;
import com.google.android.gms.location.places.ui.PlaceSelectionListener;
import com.google.android.gms.maps.CameraUpdate;
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.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import java.io.IOException;
import java.util.List;
import com.docto365.R;
public class HospitalMapsActivity extends FragmentActivity /*implements OnMapReadyCallback*/ implements LocationListener{
private GoogleMap mMap;
LocationManager location;
Toolbar mActionBarToolbar;
private static final LatLngBounds Bhubaneswar = new LatLngBounds(
new LatLng(20.192597, 85.792239), new LatLng(20.409371, 85.824544));
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hospital_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
/*SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);*/
PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)
getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
autocompleteFragment.setHint("Search Hospitals & Clinics");
autocompleteFragment.setBoundsBias(Bhubaneswar);
mActionBarToolbar=(Toolbar)findViewById(R.id.toolbar);
mActionBarToolbar.setTitle(" Hospitals & Clinics");
mActionBarToolbar.setNavigationIcon(R.drawable.ic_arrow_back);
mActionBarToolbar.setTitleTextColor(Color.WHITE);
mActionBarToolbar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
location= (LocationManager) getSystemService(Context.LOCATION_SERVICE);
location.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 400, 1000, this);
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place.
//Log.i(TAG, "Place: " + place.getName());
//Toast.makeText(HospitalMapsActivity.this, "Place: " + place.getName(), Toast.LENGTH_LONG).show();
//EditText et = (EditText) findViewById(R.id.autotext);
//String destination = et.getText().toString();
String destination = (String) place.getName();
List<Address> addressList = null;
if (destination == null || !destination.equals("")) {
Geocoder geocoder = new Geocoder(HospitalMapsActivity.this);
try {
addressList = geocoder.getFromLocationName(destination, 1);
} catch (IOException e) {
e.printStackTrace();
}
Address address = addressList.get(0);
LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
mMap.addMarker(new MarkerOptions().position(latLng).title(destination));
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
}
}
#Override
public void onError(Status status) {
// TODO: Handle the error.
//Log.i(TAG, "An error occurred: " + status);
Toast.makeText(HospitalMapsActivity.this, "An error occured: " + status, Toast.LENGTH_LONG).show();
}
});
//setUpMapIfNeeded();
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded()
{
if(mMap==null)
mMap=((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
if(mMap!=null)
setUpMap();
}
private void setUpMap()
{
//mMap.addMarker(new MarkerOptions().position(new LatLng(20.271790,85.843858)).title("Marker").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
mMap.setMyLocationEnabled(true);
//mMap.animateCamera( CameraUpdateFactory.zoomTo( 17.0f ) );
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
Toast.makeText(HospitalMapsActivity.this,"Tap on healthcare centre name to book a cab",Toast.LENGTH_LONG).show();
return false;
}
});
mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
AlertDialog.Builder dialog = new AlertDialog.Builder(HospitalMapsActivity.this);
dialog.setTitle("Book Cab");
dialog.setMessage("Do you want to book a cab?"/*HospitalMapsActivity.this.getResources().getString(R.string.gps_network_not_enabled)*/);
dialog.setPositiveButton("Book now"/*HospitalMapsActivity.this.getResources().getString(R.string.open_location_settings)*/, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
Intent i = new Intent(HospitalMapsActivity.this, Book.class);
startActivity(i);
//get gps
}
});
dialog.setNegativeButton("Later"/*HospitalMapsActivity.this.getResources().getString(R.string.open_location_settings)*/, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
//get gps
}
});
dialog.show();
}
});
LocationManager lm = (LocationManager)HospitalMapsActivity.this.getSystemService(Context.LOCATION_SERVICE);
boolean gps_enabled = false;
boolean network_enabled = false;
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch(Exception ex) {
Toast.makeText(HospitalMapsActivity.this,"Something is wrong",Toast.LENGTH_LONG).show();
}
try {
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch(Exception ex) {
Toast.makeText(HospitalMapsActivity.this,"Something is wrong",Toast.LENGTH_LONG).show();
}
if(gps_enabled==false /*&& network_enabled==false*/) {
// notify user
AlertDialog.Builder dialog = new AlertDialog.Builder(HospitalMapsActivity.this);
dialog.setTitle("Location Services Disabled");
dialog.setMessage("Please enable location services."/*HospitalMapsActivity.this.getResources().getString(R.string.gps_network_not_enabled)*/);
dialog.setPositiveButton("Enable"/*HospitalMapsActivity.this.getResources().getString(R.string.open_location_settings)*/, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
HospitalMapsActivity.this.startActivity(myIntent);
//get gps
}
});
dialog.show();
}
mMap.addMarker(new MarkerOptions().position(new LatLng(20.260423, 85.777747)).title("AMRI HOSPITALS").icon(BitmapDescriptorFactory.fromResource(R.drawable.sp)));
}
#Override
public void onLocationChanged(Location arg0) {
LatLng latLng = new LatLng(arg0.getLatitude(), arg0.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 15.0f);
mMap.animateCamera(cameraUpdate);
location.removeUpdates(this);
setUpMapIfNeeded();
//mMap.moveCamera( CameraUpdateFactory.newLatLngZoom(new LatLng(20.269556,85.841157) , 14.0f) );
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
To address your problems:
It does work on some phones (like Moto G 2nd Generation XT1068) but crashes on Lenovo A7000 whenever I search anything in the search bar and then press enter.
Please check the following:
Check if your Android platform is included in supported versions given in Android guide.
As mentioned in Google Places API - Troubleshooting, majority of the errors that your app is likely to experience are usually caused by configurations error. To get the status message for the errors that occur , call PlaceAutocomplete.getStatus() in onActivityResult() callback.
In using Place Autocomplete, please check if autocomplete is properly added to your app, as given in Place Autocomplete, using the following ways:
Add an autocomplete widget
Get place predictions programmatically
You may also check the given workaround in this GitHub post - Google Places Autocomplete does not work on mobile wherein a relevant code was placed into a function and then used the ng-focus directive to execute the expression on the desired element like:
<input id="searchBar" type="text" placeholder="Search" ng-focus="disableTap()">
Another problem I face is; I want to change the default google maps location that shows near South Africa. Change it to a specific location. How can I do that?
To change default google maps location and to get precise results, try given steps in Update your location on Google wherein you can:
Turn your location on or off, and
Check and update your location
For more information, please try going through the given documentations.
I hope one works for you.
Im developing an app using Google Maps v2 for Android and I managed to put a custom icon to the user's position but I can't remove the default one, so it overlays my custom icon like in the image:
(It is that big just for now :p )
My code is like:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
map.setMyLocationEnabled(true);
map.setOnMyLocationChangeListener(new OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
if (location == null)
return;
mPositionMarker = map.addMarker(new MarkerOptions()
.flat(true)
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.logop1))
.anchor(0.5f, 1f)
.position(new LatLng(location.getLatitude(), location.getLongitude())));
}
});
}
So:
1) Is there a way to remove the default blue dot of user's current location?
2) Will the user location be updated when I move in the "real world" (I cant test it for conectivity reasons) or do I have to write/override a method to update users position?
Thanks in advance
You will have to stop using GoogleMap.setMyLocationEnabled and write a bit more code, including having your own LocationClient and adding Circle for accuracy.
You have to do that on your own.
- set to false gmaps.getUiSettings().setMyLocationButtonEnabled(false);
create your own location button
if you get your current location, set a marker with your icon on that
if you click on your location button, move the camera and center it to the map
That will remove the blue dot
map.setMyLocationEnabled(true); remove line
Thanks joao2fast4u (lol) and ṁᾶƔƏň ツ. I followed your recomendations and I managed to make it work. Since I didn't see any answer concrete to this problem I'm posting my solution here:
package com.onsoftwares.ufvquest;
import android.location.Location;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
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;
public class MapActivity extends ActionBarActivity implements LocationListener, GooglePlayServicesClient.ConnectionCallbacks, GooglePlayServicesClient.OnConnectionFailedListener {
private GoogleMap map;
private Marker mPositionMarker;
private LocationClient mLocationClient;
private LocationRequest mLocationRequest;
private LatLng mLatLng;
private boolean mUpdatesRequested = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
mLocationClient = new LocationClient(this, this, this);
mLocationRequest = LocationRequest.create();
mLocationRequest.setInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Set the interval ceiling to one minute
mLocationRequest.setFastestInterval(1000);
// Note that location updates are off until the user turns them on
mUpdatesRequested = false;
}
#Override
protected void onStart() {
super.onStart();
mLocationClient.connect();
};
#Override
protected void onStop() {
if (mLocationClient.isConnected()) {
mLocationClient.removeLocationUpdates(this);
mLocationClient.disconnect();
}
super.onStop();
};
#Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
}
#Override
public void onConnected(Bundle arg0) {
mLocationClient.requestLocationUpdates(mLocationRequest, this);
}
#Override
public void onDisconnected() {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
// Get the current location
Location currentLocation = mLocationClient.getLastLocation();
// Display the current location in the UI
if (currentLocation != null) {
LatLng currentLatLng = new LatLng (currentLocation.getLatitude(), currentLocation.getLongitude());
if (mPositionMarker == null) {
mPositionMarker = map.addMarker(new MarkerOptions()
.position(currentLatLng)
.title("Eu")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.male_user_marker)));
map.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLatLng, 15));
} else
mPositionMarker.setPosition(currentLatLng);
}
}
}
I am working on google map api v2, and i want to make my marker draggable true,
Simply i want to drag my marker from a location and drop it on anonther one, but it taking time to focus on that marker.
Following is my code, plz suggest me where I'm doing wrong
Activity :
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
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.GoogleMap.OnMarkerDragListener;
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.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class DragMarker extends FragmentActivity implements OnMarkerDragListener {
private static GoogleMap map;
#Override
protected void onCreate(Bundle saveInstance) {
super.onCreate(saveInstance);
setContentView(R.layout.activity_test_drag_marker);
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
map.setOnMarkerDragListener(this);
//map.setOnMapLongClickListener(this);
// map.setOnMapClickListener(this);
CameraPosition INIT = new CameraPosition.Builder().target(new LatLng(19.0222, 72.8666)).zoom(17.5F).bearing(300F) // orientation
.tilt(50F) // viewing angle
.build();
// use map to move camera into position
map.moveCamera(CameraUpdateFactory.newCameraPosition(INIT));
//create initial marker
map.addMarker(new MarkerOptions().position(new LatLng(19.0216, 72.8646)).draggable(true).title("Location").snippet("First Marker")).showInfoWindow();
}
#Override
public void onMarkerDrag(Marker arg0) {
// TODO Auto-generated method stub
}
#Override
public void onMarkerDragEnd(Marker arg0) {
// TODO Auto-generated method stub
LatLng dragPosition = arg0.getPosition();
double dragLat = dragPosition.latitude;
double dragLong = dragPosition.longitude;
Log.i("info", "on drag end :" + dragLat + " dragLong :" + dragLong);
Toast.makeText(getApplicationContext(), "Marker Dragged..!", Toast.LENGTH_LONG).show();
}
#Override
public void onMarkerDragStart(Marker arg0) {
// TODO Auto-generated method stub
}
/*#Override
public void onMapClick(LatLng arg0) {
// TODO Auto-generated method stub
map.animateCamera(CameraUpdateFactory.newLatLng(arg0));
}*/
/*#Override
public void onMapLongClick(LatLng arg0) {
// TODO Auto-generated method stub
//create new marker when user long clicks
map.addMarker(new MarkerOptions().position(arg0).draggable(true));
}*/
}
XML :
<?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" />
Put the marker draggable:
Marker perth = mMap.addMarker(new MarkerOptions().position(PERTH).draggable(true));
// Creating MarkerOptions
MarkerOptions options = new MarkerOptions();
// Setting the position of the marker
options.position(point);
//set marker dragable true
options.draggable(true);
I'm having some troubles with onMarkerClick
Basically for now I just want that when ANY marker previously created starts the same activity when clicked. I will implement the filtering of the marker later on.
What I get now is no error. Simply nothing happens when the marker is clicked.
Here is my source:
I'm looping through a database to populate the map and then the markers are displayed
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class NevianoMaps extends Activity implements OnMarkerClickListener{
private GoogleMap googleMap;
DatabaseHandler db = new DatabaseHandler(this);
double latitude;
double longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.neviano_maps);
try {
// Loading map
initilizeMap();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* function to load map. If map is not created it will create it for you
* */
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
CameraPosition cameraPosition = new CameraPosition.Builder().target(
new LatLng(double value, double value)).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
//Luoghi di interesse check
if (getIntent().getIntExtra("str1", 0) == 0){
for(int x = 1; x < 6; x = x+1) {
latitude = db.getCultura(x).getCoordLat();
longitude = db.getCultura(x).getCoordLong();
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(latitude, longitude)).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
.title(db.getCultura(x).getName()));
}
}
if (getIntent().getIntExtra("str1", 1) == 1){
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(double value, double value)).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
.title("Sport"));
}
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
}
#Override
public boolean onMarkerClick(Marker arg0) {
Intent i = new Intent(this, informazioni.class);
//i.putExtra("str1", db.getCulturaName(arg0.getTitle()).getDescription());
startActivity(i);
return false;
}
#Override
protected void onResume() {
super.onResume();
initilizeMap();
}
}
Hope somebody can help! Thank you
In your initilizeMap() method, please add this line after you've got your map:
googleMap.setOnMarkerClickListener(this);