Google map v2 marker position - android

In one of my activities of an app i'm creating, I want the user to be able to click a button and once clicked a marker will be placed at the current position.
setMarker.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
// Creating a LatLng object for the current location
LatLng latLng = new LatLng(location.getLatitude(),
location.getLongitude());
googleMap.addMarker(new MarkerOptions()
.position(LatLng)
.title("Hello world"));

I am sending you some codes. Read them and use them appropriately. On your button click
private void locateMe() {
// Checking for GPS Enabled
locationManager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!isGPSEnabled) {
// GPS is disabled
askUserToEnableGPS();
}
}
/**
*
*/
private void askUserToEnableGPS() {
// Asking user to enable GPS
// 1. Instantiate an AlertDialog.Builder with its constructor
AlertDialog.Builder builder = new AlertDialog.Builder(this);
// 2. Chain together various setter methods to set the dialog
// characteristics
builder.setMessage(R.string.generic_gps_not_found)
.setTitle(R.string.generic_gps_not_found_message_title)
.setPositiveButton(R.string.generic_yes,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// User selected yes
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
})
.setNegativeButton(R.string.generic_no,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// User selected no
}
});
// 3. Get the AlertDialog from create()
AlertDialog dialog = builder.create();
dialog.show();
}
LocationListener listener = new LocationListener() {
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location arg0) {
// Setting the marker
if (googleMap == null || location == null) {
return;
} else {
googleMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(
location.getLatitude(), location.getLongitude())));
final Handler handler1 = new Handler();
handler1.postDelayed(new Runnable() {
#Override
public void run() {
// Do something after 3000ms
googleMap.animateCamera(CameraUpdateFactory.zoomTo(17));
}
}, 1000);
Marker myLocation = googleMap.addMarker(new MarkerOptions()
.position(
new LatLng(location.getLatitude(), location
.getLongitude()))
.title("Me")
.snippet("I am here")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.ic_launcher)));
}
locationManager.removeUpdates(listener);
locationManager = null;
}
};

Declare a global boolean like boolean putMarkerByButtonClick = false ; and try this
setMarker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
putMarkerByButtonClick = true ;
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 400, 1000, this);
}
});
and on your override method onLocationChange method write this :
#Override
public void onLocationChanged(Location location) {
if(putMarkerByButtonClick ){
putMarkerByButtonClick = false ;
map.addMarker(new MarkerOptions()
.position(new LatLng(location.getLatitude(), location.getLongitude()))
.title("Hello world"));
}
}

Related

Android - Google Maps - LocationListener - adding marker onLocationChanged makes app crash

I want a marker to show my current location. All permissions needed are added. When I comment out mMap.addMarker and mMap.moveCamera the app is working and Googlemaps is shown. If I let one of those two in my code the app crashes before the map even opens.
I've tried with removing the marker if it isn't null but this doesn't solve the problem.
Do you guys have any idea how I can get the app working?
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener {
private GoogleMap mMap;
private List<LatLng> fountain = null;
private LocationManager locationManager;
private double posLat;
private double posLng;
private LatLng position;
private Marker mPosition;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
startGPS();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(48.16786112327462, 16.383984438313828);
mPosition = mMap.addMarker(new MarkerOptions().position(sydney).title("Your Position").icon(BitmapDescriptorFactory.fromResource(R.drawable.location)));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
//--------------------------------------------GPS Listener---------------------------------------
public void startGPS() {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 5);
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 5, this);
onLocationChanged(locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER));
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 5: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
} else {
getDialog2("Keine Erlaubnis für GPS").show();
}
}
}
}
#Override
public void onLocationChanged(Location location) {
posLat = location.getLatitude();
posLng = location.getLongitude();
position = new LatLng(posLat, posLng);
if (mPosition != null) {
mPosition.remove();
}
mPosition = mMap.addMarker(new MarkerOptions().position(position).title("Your position").
icon(BitmapDescriptorFactory.fromResource(R.drawable.location)));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(position, 11));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
//----------------------------Helper Methods-----------------------------------------------
public Dialog getDialog2(String string) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(string);
builder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
return builder.create();
}
public Dialog getDialog(String string) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(string);
builder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
return builder.create();
}
}
Okay, I already solved the problem. So I post the solution here.
I have implemented on the MapsActivity the LocationListener interface and for some reason it doesn't work this way. I can retrieve the geocoordinates but as soon as I want to move the camera or add a marker it the app crashes as it gets opened.
I don't know why, but instead of:
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 5, this)
I undo the implementation of the LocationListener and just create a new one at the position of ,,this":
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 5, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
posLat = location.getLatitude();
posLng = location.getLongitude();
position = new LatLng(posLat, posLng);
if (mPosition != null) {
mPosition.remove();
}
mPosition = mMap.addMarker(new MarkerOptions().position(position).title("Your position").
icon(BitmapDescriptorFactory.fromResource(R.drawable.location)));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(position, 11));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
);
and this way it works without problem.

After call to ActivityCompat.requestPermissions, no dialog appears

I'm trying to implement location permissions in Android Marshmallow. I created a small test application, and everything is working perfectly. But when I copy that same code into my real application, the dialog "Allow [app name] to access this device's location?" never appears.
I can step through the debugger and see that ActivityCompat.requestPermissions() is called when it should be.
The only difference I can think of is that the real app has a lot more going on. The map activity is created from within a ScrollableTabActivity, like this:
this.addTab(getString(R.string.map), R.drawable.iconmap,
RadioStateDrawable.SHADE_GRAY,
RadioStateDrawable.SHADE_BLUE, new Intent(this, MapsActivity.class));
Do I need to think about threads, or anything like that? Or creating the activity in a different way?
Here's the full source code to the sample activity (where everything works):
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener {
private GoogleMap map;
private Button gpsButton;
private static String[] LOCATION_PERMISSIONS = {Manifest.permission.ACCESS_FINE_LOCATION};
private static int ACCESS_FINE_LOCATION_PERMISSION_REQUEST_CODE = 1;
private LocationManager locationManager;
#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);
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
gpsButton = (Button) findViewById(R.id.GPS);
gpsButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
requestLocationPermissions();
}
});
}
private void requestLocationPermissions()
{
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION))
{
new AlertDialog.Builder(MapsActivity.this)
.setMessage("Without access to your location, the app's location function cannot be used. Will you allow this access?")
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
ActivityCompat.requestPermissions(MapsActivity.this,
LOCATION_PERMISSIONS, ACCESS_FINE_LOCATION_PERMISSION_REQUEST_CODE);
}
}).setNegativeButton(R.string.no, null).show();
}
else
{
ActivityCompat.requestPermissions(this, LOCATION_PERMISSIONS, ACCESS_FINE_LOCATION_PERMISSION_REQUEST_CODE);
}
}
else
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults)
{
if (requestCode == ACCESS_FINE_LOCATION_PERMISSION_REQUEST_CODE)
{
if (verifyPermissions(grantResults))
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
else
{
new AlertDialog.Builder(MapsActivity.this)
.setMessage("Without access to your location, the app's location function cannot be used.")
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
}
}).show();
}
}
}
private void updateUserLocation(Location location)
{
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
map.moveCamera(CameraUpdateFactory.newLatLng(latLng));
locationManager.removeUpdates(this);
}
public static boolean verifyPermissions(int[] grantResults)
{
boolean verified = false;
for (int result : grantResults)
{
if (result == PackageManager.PERMISSION_GRANTED)
{
verified = true;
}
}
return verified;
}
#Override
public void onMapReady(GoogleMap googleMap)
{
map = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
map.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
map.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
#Override
public void onLocationChanged(Location location)
{
updateUserLocation(location);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
#Override
public void onProviderEnabled(String provider)
{
}
#Override
public void onProviderDisabled(String provider)
{
}
}

Why does creating a loop on my button make my android app hang?

I am writing an Android location based app. For my app i need to store my current location for every fixed time period. I create a button to start store those location using loop, but in device it hangs when start. If i remove the loop, it works. Whats the problem?
public class MainActivity extends FragmentActivity implements LocationListener {
GoogleMap googleMap;
Button btnStart,btnStop, btnstatus;
double fLat,fLon,sLat,sLon;
ArrayList<LatLng> locArray=new ArrayList<LatLng>();
int var,i;
double lat=0, lon=0;
LatLng fLL,sLL;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnStart=(Button) findViewById(R.id.btnStart);
btnStop=(Button) findViewById(R.id.btnStop);
btnstatus=(Button) findViewById(R.id.btnStatus);
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for(i=1;;i++)
{
Location loc=googleMap.getMyLocation();
double lat=loc.getLatitude();
double lon=loc.getLongitude();
LatLng latLon=new LatLng(lat, lon);
locArray.add(latLon);
}
}
});
btnStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for(i=1;i<locArray.size();i++)
{
LatLng src=locArray.get(i-1);
LatLng dest=locArray.get(i);
googleMap.addPolyline(new PolylineOptions().add(new LatLng(src.latitude, src.longitude),new LatLng(dest.latitude, dest.longitude)).width(3).color(Color.RED).geodesic(true));
}
}
});
SupportMapFragment supportMapFragment=(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
googleMap=supportMapFragment.getMap();
//googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
// googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
// googleMap.setMapType(GoogleMap.MAP_TYPE_NONE);
googleMap.setMyLocationEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onLocationChanged(Location location) {
Location loc=googleMap.getMyLocation();
double latitude=loc.getLatitude();
double longitude=loc.getLongitude();
LatLng latLon=new LatLng(latitude, longitude);
googleMap.addMarker(new MarkerOptions().position(latLon));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLon));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
And here is my Button XML:
You have an endless for loop in the btnStart:
for (i = 1;; i++)
Why do you have a loop there? There is only one location anyway. Just remove the for loop and leave the internal code.
public void onClick(View v) {
Location loc = googleMap.getMyLocation();
double lat = loc.getLatitude();
double lon = loc.getLongitude();
LatLng latLon = new LatLng(lat, lon);
locArray.add(latLon);
}
your endless loop blocks UI thread will cause ANR :
for(i=1;;i++)
You can use single boolean variable to decide where to start and where to stop fetching the locations from providers
This is example, variable is isStartedFetching
private boolean isStartedFetching = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnStart=(Button) findViewById(R.id.btnStart);
btnStop=(Button) findViewById(R.id.btnStop);
btnstatus=(Button) findViewById(R.id.btnStatus);
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isStartedFetching = true;
/* for(i=1;;i++) // this is infinite loop, so application will hang
{
Location loc=googleMap.getMyLocation();
double lat=loc.getLatitude();
double lon=loc.getLongitude();
LatLng latLon=new LatLng(lat, lon);
locArray.add(latLon);
}
} */
});
btnStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isStartedFetching = false;
for(i=1;i<locArray.size();i++)
{
LatLng src=locArray.get(i-1);
LatLng dest=locArray.get(i);
googleMap.addPolyline(new PolylineOptions().add(new LatLng(src.latitude, src.longitude),new LatLng(dest.latitude, dest.longitude)).width(3).color(Color.RED).geodesic(true));
}
}
});
SupportMapFragment supportMapFragment=(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
googleMap=supportMapFragment.getMap();
//googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
// googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
// googleMap.setMapType(GoogleMap.MAP_TYPE_NONE);
googleMap.setMyLocationEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onLocationChanged(Location location) {
if(isStartedFetching) {
Location loc=googleMap.getMyLocation();
double latitude=loc.getLatitude();
double longitude=loc.getLongitude();
LatLng latLon=new LatLng(latitude, longitude);
googleMap.addMarker(new MarkerOptions().position(latLon));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLon));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
}
You haven't set the condition for quitting the loop.
for (i = 1; ; i++)
for loop is
for (initialize to start loop; condition to stop loop; increment/decrement) {
// body of loop
}
just because you haven't put the condition when to stop,
that's why you are getting an error.

Place marker on Google Maps API once button is pressed

I am new to Android development and I am currently trying to get my app to place a maker on a current location once a button is pressed. #SuppressLint("NewApi")
public class MainActivity extends Activity implements LocationListener {
GoogleMap map;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
map.setMyLocationEnabled(true);
map.setPadding(0,200,0,0);
}
#Override
public void onLocationChanged(Location location) {
MarkerOptions mp = new MarkerOptions();
mp.position(new LatLng(location.getLatitude(), location.getLongitude()));
mp.title("my position");
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
At the moment it just drops markers every so often.
=> Because you are calling map.addMarker(mp); inside onLocationChanged() method.
Please replace the code
#Override
public void onLocationChanged(Location location) {
MarkerOptions mp = new MarkerOptions();
mp.position(new LatLng(location.getLatitude(), location.getLongitude()));
mp.title("my position");
map.addMarker(mp);
}
to
#Override
public void onLocationChanged(Location location) {
MarkerOptions mp = new MarkerOptions();
mp.position(new LatLng(location.getLatitude(), location.getLongitude()));
mp.title("my position");
}
I think your problem will be solved.
try this by replacing this code.
public class MainActivity extends Activity implements LocationListener {
GoogleMap map;
Button button;
MarkerOptions mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button_id);
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
map.setMyLocationEnabled(true);
map.setPadding(0,200,0,0);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mp.title("my position");
map.addMarker(mp);
}
}
}
#Override
public void onLocationChanged(Location location) {
mp = new MarkerOptions();
mp.position(new LatLng(location.getLatitude(), location.getLongitude()));
mp.title("my position");
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
remove map.addMarker(mp) from onLocationChanged() method because it adds marker to the map every time a location change event is triggered.

Getting user current location on google mapview

Hi I have been trying to get and pinpoint the location of the phone (user current location) however I have no luck. I hope somebody can help me with the code.
Just to add some more, I am receiving a "Couldn't get connection factory client" error. Does this have something to do with the ability to return the user location?
If it helps I have been following the tutorial by thenewboston.
Or does this have something to do with my API key? But I can receive the map properly, but cannot pinpoint the user's current location
The main code:
public class Map extends MapActivity implements LocationListener{
MapView map;
long start;
long stop;
MyLocationOverlay compass;
MapController controller;
int x,y;
GeoPoint touchedPoint;
Drawable d;
List<Overlay> overlayList;
LocationManager lm;
LocationListener ll;
String towers;
int lat = 0;
int longi = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
map = (MapView)findViewById(R.id.mapview);
map.setBuiltInZoomControls(true);
touch t = new touch();
overlayList = map.getOverlays();
overlayList.add(t);
compass = new MyLocationOverlay(Map.this, map);
overlayList.add(compass);
controller = map.getController();
GeoPoint point = new GeoPoint(832332,4121093);
controller.animateTo(point);
controller.setZoom(8);
d = getResources().getDrawable(R.drawable.pointer);
//placing location
lm =(LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria crit = new Criteria();
towers = lm.getBestProvider(crit, false);
Location loc = lm.getLastKnownLocation(towers);
if(loc != null){
lat = (int) (loc.getLatitude() *1E6);
longi = (int)(loc.getLongitude()*1E6);
GeoPoint location = new GeoPoint(lat, longi);
OverlayItem overlayitem = new OverlayItem(location , "wassup", "2nd string");
CustomPinPoint custom = new CustomPinPoint(d, Map.this);
custom.insertPinPoint(overlayitem);
overlayList.add(custom);
}else{
Toast.makeText(Map.this, "Location is null", Toast.LENGTH_LONG).show();
lm.requestLocationUpdates(towers, 1500, 1, this);
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
compass.disableCompass();
super.onPause();
lm.removeUpdates(this);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
compass.enableCompass();
super.onResume();
lm.requestLocationUpdates(towers, 500, 1, this);
}
I think you can ignore the alertdialog
public class touch extends Overlay {
public boolean onTouchEvent(MotionEvent e, MapView m){
if(e.getAction()== MotionEvent.ACTION_DOWN){
start = e.getEventTime();
x = (int) e.getX();
y = (int) e.getY();
touchedPoint = map.getProjection().fromPixels(x, y);
}
if(e.getAction()== MotionEvent.ACTION_UP){
stop = e.getEventTime();
}
if(stop-start >1200){
AlertDialog alert = new AlertDialog.Builder(Map.this).create();
alert.setTitle("Option");
alert.setMessage("Pick the option");
alert.setCanceledOnTouchOutside(true);
alert.setButton("Place pointer pinpoint",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
OverlayItem overlayitem = new OverlayItem(touchedPoint , "wassup", "2nd string");
CustomPinPoint custom = new CustomPinPoint(d, Map.this);
custom.insertPinPoint(overlayitem);
overlayList.add(custom);
}
});
alert.setButton2("Get address",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Geocoder geocoder = new Geocoder(getBaseContext(), Locale.getDefault());
try{
List<Address> address = geocoder.getFromLocation(touchedPoint.getLatitudeE6()
/1E6, touchedPoint.getLongitudeE6() /1E6, 1);
if (address.size()>0){
String display = "";
for(int i=0 ; i<address.get(0).getMaxAddressLineIndex(); i++){
display +=address.get(0).getAddressLine(i) + "\n";
}
Toast t = Toast.makeText(getBaseContext(), display, Toast.LENGTH_LONG);
t.show();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
}
}
});
alert.setButton3("Toggle View",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
if(map.isSatellite()){
map.setSatellite(false);
map.setStreetView(true);
}else{
map.setStreetView(false);
map.setSatellite(true);
}
}
});
alert.show();
return true;
}
return false;
}
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_map, menu);
return true;
}
#Override
public void onLocationChanged(Location l) {
// TODO Auto-generated method stub
lat = (int)(l.getLatitude()*1E6);
longi = (int)(l.getLongitude()*1E6);
GeoPoint location = new GeoPoint(lat, longi);
OverlayItem overlayitem = new OverlayItem(location , "wassup", "2nd string");
CustomPinPoint custom = new CustomPinPoint(d, Map.this);
custom.insertPinPoint(overlayitem);
overlayList.add(custom);
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
The CustomPinPoint code :
public class CustomPinPoint extends ItemizedOverlay<OverlayItem> {
private ArrayList<OverlayItem> pinpoints = new ArrayList<OverlayItem>();
private Context c;
// tesst google code
public CustomPinPoint(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
// TODO Auto-generated constructor stub
}
public CustomPinPoint(Drawable defaultMarker, Context context) {
// TODO Auto-generated constructor stub
this(defaultMarker); //original code
}
#Override
protected OverlayItem createItem(int i) {
// TODO Auto-generated method stub
return pinpoints.get(i);
}
#Override
public int size() {
// TODO Auto-generated method stub
return pinpoints.size();
}
public void insertPinPoint(OverlayItem item){
pinpoints.add(item);
// this.populate(); // original code
// test code
populate();
}
#Override
protected boolean onTap(int index){
OverlayItem item = pinpoints.get(index);
AlertDialog.Builder dialog = new AlertDialog.Builder(c);
dialog.setTitle(item.getTitle());
dialog.setMessage(item.getSnippet());
dialog.show();
return true;
}
public void addOverlay(OverlayItem overlay) {
// TODO Auto-generated method stub
pinpoints.add(overlay);
populate();
}
}
XML code:
<com.google.android.maps.MapView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/mapview"
android:enabled="true"
android:clickable="true"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:apiKey="0t9rHfGlUPgisa8P9MRAsSxhRXTVCL0XJog7uiA"
/>
Here is the example how to do that easily, try to implement this logic into your project:
public class MyMapActivity extends MapActivity {
private MapView map;
private MapController controller;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mymap);
initMapView();
initMyLocation();
map.invalidate();
}
private void initMapView() {
map = (MapView) findViewById(R.id.map);
controller = map.getController();
map.setSatellite(true);
map.setBuiltInZoomControls(true);
}
private void initMyLocation() {
final MyLocationOverlay overlay = new MyLocationOverlay(this, map);
overlay.enableMyLocation();
//overlay.enableCompass(); // does not work in emulator
overlay.runOnFirstFix(new Runnable() {
public void run() {
// Zoom in to current location
controller.setZoom(15);
controller.animateTo(overlay.getMyLocation());
}});
}
}
Well this is embarrassing, it turns out that my code is correct and the problem was that the device's GPS wasn't turned on. Well I hope my code can help anyone in need. Cheers!

Categories

Resources