Ok i have tried Nicholas's solution but still getting force close if i press the back button as the app searches for gps fix.so i m uploading all the codes and files(except icon.png and pen.png in drawables) for the project...so that it's possible just to copy paste the code from here to see whats going on. my main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/icon"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello"
/>
<Button android:text="Start"
android:id="#+id/Button01"
android:layout_width="120px"
android:layout_height="70px"
android:layout_gravity = "center_horizontal"
android:textSize="20px"
android:layout_marginTop="150px"
android:clickable="true"
></Button>
</LinearLayout>
next my main activity(GpsLocEx.java)
package com.example.gpslocex;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class GpsLocEx extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button start = (Button) findViewById(R.id.Button01);
start.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent map = new Intent(view.getContext(), com.example.gpslocex.ShowMap.class);
startActivityForResult(map, 0);
}
});
}
}
next my gps.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/mainlayout"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<com.google.android.maps.MapView
android:id="#+id/mapview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clickable="true"
android:apiKey="06ZLf-HkdkRMb513KS2ZRljmMQL0bntlyMJ-rOQ"
/>
</RelativeLayout>
next ShowMap.java
package com.example.gpslocex;
import java.util.List;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
public class ShowMap extends MapActivity {
private MapController mapController;
private MapView mapView;
private LocationManager locationManager;
private GeoUpdateHandler geoUpdateHandler;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gps);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mapView.setSatellite(true);
mapController = mapView.getController();
mapController.setZoom(14); // Zoom 1 is world view
geoUpdateHandler = new GeoUpdateHandler();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
createGpsDisabledAlert();
} else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0,geoUpdateHandler);
}
}
private void createGpsDisabledAlert() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder
.setMessage(
"Your GPS is disabled! Would you like to enable it?")
.setCancelable(false).setPositiveButton("Enable GPS",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
showGpsOptions();
}
});
builder.setNegativeButton("Do nothing",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
private void showGpsOptions() {
Intent gpsOptionsIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsOptionsIntent);
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
public class GeoUpdateHandler implements LocationListener {
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude() * 1E6);
int lng = (int) (location.getLongitude() * 1E6);
GeoPoint point = new GeoPoint(lat, lng);
mapController.animateTo(point); // mapController.setCenter(point);
MapOverlay mapOverlay = new MapOverlay();
mapOverlay.setPointToDraw(point);
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
class MapOverlay extends Overlay
{
private GeoPoint pointToDraw;
public void setPointToDraw(GeoPoint point) {
pointToDraw = point;
}
public GeoPoint getPointToDraw() {
return pointToDraw;
}
#Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when) {
super.draw(canvas, mapView, shadow);
// convert point to pixels
Point screenPts = new Point();
mapView.getProjection().toPixels(pointToDraw, screenPts);
// add marker
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.pen);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y - 128, null);
return true;
}
}
#Override
public void onPause() {
locationManager.removeUpdates(geoUpdateHandler);
}
}
next strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Version-1.0</string>
<string name="app_name">GpsLocEx</string>
</resources>
Finally AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.gpslocex"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="#drawable/icon" android:label="#string/app_name">
<uses-library android:name="com.google.android.maps" />
<activity android:name=".GpsLocEx"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".ShowMap"></activity>
</application>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="ACCESS_COARSE_LOCATION" />
</manifest>
You can use the Android lifecycle methods to turn off the GPS when the Activity is no longer on top.
Use onPause(), onStop(), or onDestroy() to remove updates from your locationManager. Something like this:
#Override
public void onPause() {
locationManager.removeUpdates(myLocationListener);
}
EDIT:
You have a ClassCastException in your onPause() method. You cannot cast this (your Activity) to a LocationListener (at least not without making your Activity implement LocationListener).
In your code, you create a new GeoUpdateHandler(). First, you should create an instanceVariable that is your GeoUpdateHandler. Underneath your instance variable for LocationManager, create one like this:
private GeoUpdateHandler geoUpdateHandler;
You should keep a handle to this in the onCreate() method:
#Override
public void onCreate(Bundle savedInstanceState) {
//...some code here...
geoUpdateHandler = new GeoUpdateHandler();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0,geoUpdateHandler);
//...maybe some more code here...
}
And then in the onPause, pass the geoUpdateHandler to the removeUpdates function:
#Override
public void onPause() {
locationManager.removeUpdates(geoUpdateHandler);
}
EDIT 2:
The stacktrace says it all:
android.app.SuperNotCalledException: Activity {com.example.gpslocnav6ex/com.example.gpslocnav6ex.ShowMap} did not call through to super.onPause()
Call through to super.onPause() in your onPause()
#Override
public void onPause() {
super.onPause();
locationManager.removeUpdates(geoUpdateHandler);
}
Try this locationManager.removeUpdates(myLocationListener);
Your should write it in onPause()
#Override
protected void onPause()
{
// TODO Auto-generated method stub
super.onPause();
locationManager.removeUpdates(myLocationListener);
}
This will turn off GPS when your exit from your application .
Related
If I click "Find My Location" button, then my location information should have shown on the TextView, but doesn't work.
It's simple code but I have no idea where did this go wrong. Seems that there's no mistake within the code.. could be the problem of my phone?
MainActivity.java
package org.androidtown.mylocation;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
}
public void onButton1Clicked(View v){
LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
long minTime = 10000;
float minDistance = 0;
MyLocationListener listener = new MyLocationListener();
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
minTime, minDistance, listener);
manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
minTime, minDistance, listener);
Location lastLocation = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (lastLocation != null){
Double latitude = lastLocation.getLatitude();
Double longitude = lastLocation.getLongitude();
textView.setText("My Latest Location: " + latitude + ", " + longitude);
textView.invalidate();
}
}
class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
Double latitude = location.getLatitude();
Double longitude = location.getLongitude();
textView.setText("My Location: " + latitude + ", " + longitude);
textView.invalidate();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.androidtown.mylocation" >
<!-- GPS -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<!-- NETWORK -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
activity_main.xml
<RelativeLayout 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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Find My Location"
android:id="#+id/button"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:onClick="onButton1Clicked" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="My Location"
android:id="#+id/textView"
android:layout_below="#+id/button"
android:layout_centerHorizontal="true"
android:layout_marginTop="83dp" />
</RelativeLayout>
Hi I'm currently learning about the GPS for development in Android. Now I've read about the basics through vogellas blog here. Now I already get the latitude and longitude and displayed it on my device but I don't know why it doesn't update my location even though I already set a runnable thread to fetch location every 3 seconds. Same reason why I can't check if I got the correct formula to get the total distance I've travelled.
This is my first time working with this so maybe someone can give me a tip or idea on how to.
I created a repository in github maybe someone can help me with this. See file here :)
EDIT:
Okay the main problem is that the onChangeLocation() seems doesn't work on my end. What I tried is to create a runnable to display the location every 3 seconds but it doesn't return the result I expected.
Did I missed out on something here?
Here's my code so far for easier viewing:
Main.java
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.provider.Settings;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
/*created by Kahel 08/16/2013
* to read more about the location manager go here: http://www.vogella.com/articles/AndroidLocationAPI/article.html
*
* */
public class Main extends Activity implements LocationListener {
private TextView latitude, longitude, distance;
private Button getLocation;
private LocationManager locationManager;
private String provider;
double distance_travelled;
double latitude_prev;
double longitude_prev;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
latitude = (TextView)findViewById(R.id.txt_latitude);
longitude = (TextView)findViewById(R.id.txt_longitude);
distance = (TextView) findViewById(R.id.txt_distance);
getLocation = (Button)findViewById(R.id.btn_getLocation);
checkGps();
getCurrentLocation();
getLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
locatorRunner();
}
});
}
private void locatorRunner(){
Thread thread = new Thread()
{
#Override
public void run() {
try {
while(true) {
sleep(3000);
runOnUiThread(new Runnable() {
#Override
public void run() {
/*needs UI Thread*/
getCurrentLocation();
}
});
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
}
private void getCurrentLocation(){
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
Toast.makeText(Main.this,String.valueOf(location),Toast.LENGTH_SHORT).show();
//locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000L,500.0f, (LocationListener) location);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
latitude.setText("Location not available");
longitude.setText("Location not available");
distance.setText("0");
}
}
private void checkGps(){
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER);
Toast.makeText(Main.this,String.valueOf(enabled),Toast.LENGTH_SHORT).show();
// Check if enabled and if not send user to the GSP settings
// Better solution would be to display a dialog and suggesting to
// go to the settings
if (!enabled) {
showGpsSettingDialog();
}
}
private void showGpsSettingDialog(){
/*Create a dialog to tell user to enable his GPS settings to pinpoint his or her location*/
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Main.this);
alertDialog.setTitle("Settings para sa lokasyon"); /*should be on a string values*/
alertDialog
.setMessage("Kasalukuyang hindi aktibo ang iyong GPS para makuha ang iyong lokasyon. Nais mo bang i-set ito ngayon?")
.setCancelable(false)
.setPositiveButton("Oo", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
})
.setNegativeButton("Hindi", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
AlertDialog gpsSettingsDialog = alertDialog.create();
gpsSettingsDialog.show();
}
/* Request updates at startup */
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#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) {
getLocation(location);
}
private void getLocation(Location location){
int R = 6371;
double lat = location.getLatitude();
double lon = location.getLongitude();
latitude_prev = lat;
longitude_prev = lon;
Double dlat = latitude_prev - lat;
Double dlon = longitude_prev - lon;
double a = Math.sin(dlat / 2) * Math.sin(dlat / 2) + Math.cos(latitude_prev) *
Math.cos(lat) * Math.sin(dlon / 2) * Math.sin(dlon / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
distance_travelled = R * c;
latitude.setText(String.valueOf(lat));
longitude.setText(String.valueOf(lon));
distance.setText(String.valueOf(distance_travelled));
}
/*private double toRad(double d) {
return d * Math.PI / 180;
}*/
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
Toast.makeText(this, "Enabled new provider " + provider,Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String s) {
Toast.makeText(this, "Disabled provider " + provider,Toast.LENGTH_SHORT).show();
}
}
main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dip"
android:orientation="horizontal" >
<TextView
android:id="#+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:layout_marginRight="5dip"
android:text="Latitude: "
android:textSize="20dip" >
</TextView>
<TextView
android:id="#+id/txt_latitude"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="unknown"
android:textSize="20dip" >
</TextView>
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout2"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/TextView03"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:layout_marginRight="5dip"
android:text="Longitute: "
android:textSize="20dip" >
</TextView>
<TextView
android:id="#+id/txt_longitude"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="unknown"
android:textSize="20dip" >
</TextView>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Distance Travelled:"
android:id="#+id/textView"
android:layout_gravity="left|center_vertical"
android:layout_marginLeft="10dp"
android:layout_marginRight="5dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="unknown"
android:id="#+id/txt_distance"/>
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get Location"
android:id="#+id/btn_getLocation"
android:layout_gravity="center"/>
</LinearLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.geolocation"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION " />
<uses-permission android:name="android.permission.INTERNET" />
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="10" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.geolocation.Main"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Note:
I added the button Start Tracking because I'm not sure if the onLocationChanged is working or not. hahaha!
Basic approach for distance:
public class test extends Activity implements LocationListener{
private LocationManager lm;
private Location last;
private long distance;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
lm = (LocationManager) getSystemService(LOCATION_SERVICE);
}
#Override
protected void onResume() {
super.onResume();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,1,this);
}
#Override
protected void onPause() {
super.onPause();
lm.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
if(last != null){
distance += location.distanceTo(last);
}
last = new Location(location);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
}
You have to implement LocationListener to get current GPS location something like this :
Set user permission firlst
Now get GPS location like this :
LocationManager locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new MyLocationListener();
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0, locationListener);
/*----------Listener class to get coordinates ------------- */
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
//Get your location here
}
#Override
public void onProviderDisabled(String provider) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
}
You can call getCurrentLocation() every 3 second but this will not trigger getLocation(location);.
getLocation(location); will be called only when Location gets updated
#Override
public void onLocationChanged(Location location) {
getLocation(location);
}
I'm using mapview. I got RSA KEY and I used that key. The following codes :
main.xml
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.maps.MapView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/mapview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:apiKey="rsa key is here"
android:clickable="true" />
MainActivity.java
import java.util.List;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.widget.Toast;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
public class MainActivity extends MapActivity {
private final int is_Enabled_GPS = 0;
private LocationManager locManager;
private LocationListener locListener;
private MapView mapView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
GeoPoint nokta = new GeoPoint((int) (38 * 1e6), (int) (36 * 1e6));
mapView.getController().setCenter(nokta);
locListener = new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
locManager.removeUpdates(locListener);
if(location != null){
final GeoPoint nokta = new GeoPoint((int) (location.getLatitude() * 1e6), (int) (location.getLongitude() * 1e6));
Overlay konumum = new Overlay() {
#Override
public boolean draw(android.graphics.Canvas canvas, MapView mapView, boolean shadow, long when){
super.draw(canvas, mapView, shadow);
Point screenPts = new Point();
mapView.getProjection().toPixels(nokta, screenPts);
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y,null);
return true;
}
};
List<Overlay> mapOverlays = mapView.getOverlays();
mapOverlays.clear();
mapOverlays.add(konumum);
mapView.getController().setCenter(nokta);
mapView.preLoad();
}
else{
Toast.makeText(getApplicationContext(), "Konum Bulunamadı", Toast.LENGTH_LONG).show();
}
}
};
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.karakose.gps"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.karakose.gps.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<uses-library android:name="com.google.android.maps" />
</application>
When I try to run on the phone, it seems the lower left corner of the Google logo and a white area. What I'm doing wrong ?
I'm very new to android. I'm developing an app which shows the current location using Google Map.
I've generated key for this application. But It doesn't show the map instead, it shows Grid View.
The following is the code..!
//MActivity
package velu.ndot.hosp;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
public class HospitalActivity extends MapActivity {
private LocationManager myLocationManager;
private LocationListener myLocationListener;
private TextView myLongitude, myLatitude;
private MapView myMapView;
private SeekBar myZoomBar;
private MapController myMapController;
private void CenterLocation(GeoPoint centerGeoPoint)
{
myMapController.animateTo(centerGeoPoint);
myLongitude.setText("Longitude: "+
String.valueOf((float)centerGeoPoint.getLongitudeE6()/1000000)
);
myLatitude.setText("Latitude: "+
String.valueOf((float)centerGeoPoint.getLatitudeE6()/1000000)
);
};
private void SetZoomLevel()
{
int myZoomLevel = myZoomBar.getProgress()+1;
myMapController.setZoom(myZoomLevel);
Toast.makeText(this,
"Zoom Level : " + String.valueOf(myZoomLevel),
Toast.LENGTH_LONG).show();
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newtab);
myMapView = (MapView)findViewById(R.id.mapview);
myLongitude = (TextView)findViewById(R.id.longitude);
myLatitude = (TextView)findViewById(R.id.latitude);
myZoomBar = (SeekBar)findViewById(R.id.zoombar);
myMapView.setSatellite(true); //Set satellite view
myMapController = myMapView.getController();
SetZoomLevel();
myLocationManager = (LocationManager)getSystemService(
Context.LOCATION_SERVICE);
myLocationListener = new MyLocationListener();
myLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
0,
0,
myLocationListener);
//Get the current location in start-up
//check LastKnownLocation, if not valid, skip it.
Location initLocation=
myLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(initLocation != null)
{
GeoPoint initGeoPoint = new GeoPoint(
(int)(initLocation.getLatitude()*1000000),
(int)(initLocation.getLongitude()*1000000));
CenterLocation(initGeoPoint);
}
myZoomBar.setOnSeekBarChangeListener(myZoomBarOnSeekBarChangeListener);
}
private SeekBar.OnSeekBarChangeListener myZoomBarOnSeekBarChangeListener =
new SeekBar.OnSeekBarChangeListener(){
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
SetZoomLevel();
}
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
};
private class MyLocationListener implements LocationListener{
public void onLocationChanged(Location argLocation) {
// TODO Auto-generated method stub
GeoPoint myGeoPoint = new GeoPoint(
(int)(argLocation.getLatitude()*1000000),
(int)(argLocation.getLongitude()*1000000));
CenterLocation(myGeoPoint);
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider,
int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
};
//Manifest file
This is my manifest.xml File and I have got permission with the internet
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="velu.ndot.hosp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:theme="#android:style/Theme.Light"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".HospitalActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<uses-library android:required="true" android:name="com.google.android.maps"> </uses-library>
</application>
</manifest>
//Layout
My layout design..!
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<TextView
android:id="#+id/longitude"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Longitude:"
/>
<TextView
android:id="#+id/latitude"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Latitude:"
/>
<SeekBar
android:id="#+id/zoombar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="20"
android:progress="0"/>
</LinearLayout>
<com.google.android.maps.MapView
android:id="#+id/mapview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clickable="false"
android:apiKey="key**********************"
/>
</LinearLayout>
This looking all right in your code. Please try to take another map key and then check may be this will solve your problem .
As your code is similar to:
http://www.mubasheralam.com/tutorials/android/how-use-google-maps-android-application
I am developing one application which displays
current location of user also displays doctors
on near by him on google map.I developed one
demo application which can find any location
and put a marker on it but I don't know how to
find near by addresses which are stored in database.
**My XML File:**
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:layout_width="fill_parent"
android:layout_alignParentBottom="true"
android:layout_height="wrap_content"
android:orientation="vertical">
<EditText
android:layout_width="fill_parent"
android:id="#+id/location"
android:layout_height="wrap_content"
android:text="White House" />
<Button
android:id="#+id/geocodeBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Find Location" />
</LinearLayout>
<com.google.android.maps.MapView
android:id="#+id/mapview"
android:layout_width="fill_parent"
android:layout_height="320px"
android:clickable="true"
android:apiKey=Z1oyeAgSpj5vGQVD6ADrUI2622o7yfJVJ3vEOA"
/>
</RelativeLayout>
**Manifest File:**
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="pkg.Map"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="7" />
<application
android:icon="#drawable/icon"
android:label="#string/app_name">
<uses-library
android:name="com.google.android.maps">
</uses-library>
<activity
android:name="pkg.GeoCoderWithMarkers.GeoCoder"
android:label="#string/app_name">
<intent-filter>
<action
android:name="android.intent.action.MAIN" />
<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission
android:name="android.permission.INTERNET"/>
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission
android:name="android.permission.ACCESS_COARSE_LOCATION"/>
</manifest>
and Java File:
package pkg.GeoCoderWithMarkers;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import pkg.Map.R;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Geocoder;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.OverlayItem;
public class GeoCoder extends MapActivity {
private MapController mapController;
private MapView mapView;
GeoPoint p,p1;
private MyLocationOverlay me=null;
private LocationManager locationManager;
private Geocoder geocoder = null;
int lat;
int lng;
//** Called when the activity is first created. *//*
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapView = (MapView)findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
GeoPoint pt = new GeoPoint((int)(5.34079*1000000),
(int)(100.28241*1000000));
mapView.getController().setZoom(10);
mapView.setStreetView(true);
mapView.getController().setCenter(pt);
Button geoBtn =(Button)findViewById(R.id.geocodeBtn);
geocoder = new Geocoder(this);
final Drawable marker=getResources().getDrawable
(R.drawable.pushpin_blue);
int markerWidth = marker.getIntrinsicWidth();
int markerHeight = marker.getIntrinsicHeight();
marker.setBounds(0, markerHeight, markerWidth, 0);
MyItemizedOverlay myItemizedOverlay =
new MyItemizedOverlay(marker);
mapView.getOverlays().add(myItemizedOverlay);
GeoPoint myPoint1 = new GeoPoint(lat,
(int)(100.28241*1000000));
myItemizedOverlay.addItem(myPoint1,
"myPoint1", "myPoint1");
GeoPoint myPoint2 = new GeoPoint
(50*1000000, 50*1000000);
myItemizedOverlay.addItem
(myPoint2, "myPoint2", "myPoint2");
geoBtn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
try {
EditText loc =
(EditText)findViewById(R.id.location);
String locationName = loc.getText().toString();
List<Address> addressList =
geocoder.getFromLocationName
(locationName, 5);
if(addressList!=null && addressList.size()>0)
{
int lat = (int)(addressList.get(0).
getLatitude()*1000000);
int lng = (int)(addressList.get(0).
getLongitude()*1000000);
GeoPoint pt = new GeoPoint(lat,lng);
mapView.getController().setZoom(17);
mapView.getController().setCenter(pt);
MyItemizedOverlay myItemizedOverlay =
new MyItemizedOverlay(marker);
mapView.getOverlays().add(myItemizedOverlay);
GeoPoint myPoint1 = new GeoPoint(lat, lng);
myItemizedOverlay.addItem
(myPoint1, "myPoint1", "myPoint1");
// GeoPoint myPoint2 = new GeoPoint
(50*1000000, 50*1000000);
// myItemizedOverlay.addItem
(myPoint2, "myPoint2", "myPoint2");
}
} catch (IOException e) {
e.printStackTrace();
}
}});
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
}
class MyItemizedOverlay extends
ItemizedOverlay<OverlayItem>{
private ArrayList<OverlayItem>
overlayItemList = new ArrayList<OverlayItem>();
public MyItemizedOverlay(Drawable marker) {
super(boundCenterBottom(marker));
// TODO Auto-generated constructor stub
populate();
}
public void addItem(GeoPoint p,
String title, String snippet){
OverlayItem newItem =
new OverlayItem(p, title, snippet);
overlayItemList.add(newItem);
populate();
}
#Override
protected OverlayItem createItem(int i) {
// TODO Auto-generated method stub
return overlayItemList.get(i);
}
#Override
public int size() {
// TODO Auto-generated method stub
return overlayItemList.size();
}
#Override
public void draw(Canvas canvas,
MapView mapView, boolean shadow) {
// TODO Auto-generated method stub
super.draw(canvas, mapView, shadow);
//boundCenterBottom(marker);
}
}
The Location-Class offers you a pretty nice Method: distanceTo(GeoPoint).
So just iterate through your doctor's GeoPoints with this Method.
you can define the specific radius and calculate the distance from your location to doctors addresses and find the distance and as per radius set and check whether it's in radius or not then show the near by doctor addresses.
For this you need to check every time when the location was change into the service so you can found the near by locations.