I am trying to get the address of a location. But the app does not show anything, only black screen.
I checked my Key, Android Manifest file. And everything on place.
package in.isuru.maps;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
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.MyLocationOverlay;
import com.google.android.maps.Overlay;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.view.MotionEvent;
import android.widget.Toast;
public class Main extends MapActivity {
MapView map;
long start;
long stop;
MyLocationOverlay compass;
MapController controller;
GeoPoint touchPoint;
int x, y;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
map = (MapView)findViewById(R.id.map_view_main);
map.setBuiltInZoomControls(true);
Touchy t = new Touchy();
List<Overlay> overlayList = map.getOverlays();
overlayList.add(t);
compass = new MyLocationOverlay(Main.this, map);
overlayList.add(compass);
//controller = map.getController();
//GeoPoint point = new GeoPoint(7865444, 79819940);
//controller.animateTo(point);
//controller.setZoom(6);
}
#Override
protected void onPause() {
compass.disableCompass();
super.onPause();
}
#Override
protected void onResume() {
compass.enableCompass();
super.onResume();
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
class Touchy 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();
touchPoint = map.getProjection().fromPixels(x, y);
}
if(e.getAction() == MotionEvent.ACTION_UP){
stop = e.getEventTime();
}
if(stop - start > 1500){
AlertDialog alert = new AlertDialog.Builder(Main.this).create();
alert.setTitle("Pick an Option");
alert.setMessage("Set the Place");
alert.setButton("Place a Pin", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
}
});
alert.setButton2("Get Address", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
Geocoder geocoder = new Geocoder(getBaseContext(), Locale.getDefault());
try{
List<Address> address = geocoder.getFromLocation(touchPoint.getLatitudeE6()/1E6, touchPoint.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("Place a Pin", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
}
});
alert.show();
return true;
}
return false;
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="in.isuru.maps"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<uses-library android:name="com.google.android.maps" android:required="true"/>
<activity
android:name=".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>
I tried to add fake longitudes and latitude via Emulator control but it does not show anything either.
I think the error is not of Google Map its a problem because of the Geocoder class.
Please try your code with actual device and not in emulator and I am sure it will work.
As its found that Geocoder class doesn't work well in emulator.
Related
When I press the button btnlocation it should go to the Mapsactivity
but it is giving me the error:
java.lang.NoClassDefFoundError
I also added MapsActivity in manifest as usual .. .but why this error? I need the solution.Can any one help me please...
package com.mamun.tasktest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
public class FragmentB extends Fragment implements OnClickListener {
private Button btnLocation;
private LocationManager manager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.frag_b, null, false);
btnLocation = (Button) view.findViewById(R.id.btnLocation);
btnLocation.setOnClickListener(this);
manager = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("GPS is currently disabled");
builder.setMessage("Please enable GPS for better view of your location.\nWould you like to change these settings now?");
builder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(i);
}
});
builder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
getActivity();
}
});
builder.create().show();
}
return view;
}
#Override
public void onClick(View v) {
if(isMapAvailalble()){
/////////////////////////////
/*
// */
//////////////////////////
Intent in = new Intent(getActivity(),MapsActivity.class);
startActivity(in);
}
}
/*Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE"); intent.putExtra("enabled", false);
sendBroadcast(intent);*/
//if googleplayservis or play store is not available/updated or user recoverable problem occured.
public boolean isMapAvailalble()
{
// to test if there is no googleplayservise
//int resultcode=ConnectionResult.SERVICE_MISSING;
int resultcode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());
if(ConnectionResult.SUCCESS==resultcode)
{
return true;
}
else if(GooglePlayServicesUtil.isUserRecoverableError(resultcode))
{
Dialog d = GooglePlayServicesUtil.getErrorDialog(resultcode, getActivity(), 1);
d.show();
}
else
{
Toast.makeText(getActivity()," Google Map API is not supported in your device",Toast.LENGTH_LONG).show();
}
return false;
}
/*public void turnGPSOn()
{
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
((Context) this.ctx).sendBroadcast(intent);
#SuppressWarnings("deprecation")
String provider = Settings.Secure.getString(((Context) ctx).getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(!provider.contains("gps")){ //if gps is disabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
((Context) this.ctx).sendBroadcast(poke);
}*/
}
Manifest.xml file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mamun.tasktest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="16" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="com.mamun.tasktest.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-library android:name="com.google.android.maps"/>
<permission
android:name="com.mamun.tasktest.permission.MAPS_RECEIVE"
android:protectionLevel="signature" >
</permission>
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.mamun.tasktest.MainActivity"
android:label="#string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyCgGng3iaqbTxJ3B_lYemZBEqXOonUtFEI" />
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity android:name="MapsActivity"></activity>
</application>
</manifest>
MapsActivity
package com.mamun.tasktest;
import java.io.IOException;
import java.util.ArrayList;
import android.app.Activity;
import android.graphics.Canvas;
import android.graphics.Point;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
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.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.maps.MapActivity;
public class MapsActivity<GeoPoint, OverlayItem> extends MapActivity implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener, LocationListener {
MapView mapView;
com.google.android.maps.GeoPoint p;
private LocationManager manager;
private TextView tvAddress;
private Button btnSearch;
private EditText etSearch;
private LocationClient locationClient;
private GoogleMap googleMap;
private MapFragment mapFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
manager = (LocationManager) getSystemService(LOCATION_SERVICE);
tvAddress = (TextView) findViewById(R.id.tvaddress);
btnSearch = (Button) findViewById(R.id.btnSearch);
etSearch = (EditText) findViewById(R.id.etSearch);
mapFragment = (MapFragment) getFragmentManager().findFragmentById(
R.id.maps);
googleMap = mapFragment.getMap();
locationClient = new LocationClient(this, this, this);
}
public void onSearch(View v) {
// Getting user input location
String location = etSearch.getText().toString();
if (location != null && !location.equals("")) {
new GeocoderTask().execute(location);
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
locationClient.connect();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
locationClient.disconnect();
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onConnectionFailed(ConnectionResult result) {
}
#Override
public void onConnected(Bundle connectionHint) {
try {
Location currentLocation = locationClient.getLastLocation();
double lat = currentLocation.getLatitude();
double lng = currentLocation.getLongitude();
// txtLocation.setText(lat + ", " + lng);
Geocoder geocoder = new Geocoder(this);
ArrayList<Address> address = (ArrayList<Address>) geocoder
.getFromLocation(currentLocation.getLatitude(),
currentLocation.getLongitude(), 5);
Address addr = address.get(0);
String currentAddress = (addr.getAddressLine(0) + "-"
+ addr.getAdminArea() + "-" + addr.getLocality() + "-"
+ addr.getPostalCode() + "-" + addr.getCountryCode());
MarkerOptions options = new MarkerOptions();
options.position(new LatLng(lat, lng));
options.title(currentAddress);
options.snippet("Current location");
options.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
if (googleMap != null) {
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(lat, lng), 14.0f));
googleMap.addMarker(options);
} else {
Toast.makeText(getApplicationContext(), "Map is null",
Toast.LENGTH_LONG).show();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onDisconnected() {
// TODO Auto-generated method stub
}
// An AsyncTask class for accessing the GeoCoding Web Service
private class GeocoderTask extends
AsyncTask<String, Void, ArrayList<Address>> {
#Override
protected ArrayList<Address> doInBackground(String... locationName) {
// Creating an instance of Geocoder class
Geocoder geocoder = new Geocoder(getBaseContext());
ArrayList<Address> addresses = null;
try {
// Getting a maximum of 3 Address that matches the input text
addresses = (ArrayList<Address>) geocoder.getFromLocationName(
locationName[0], 3);
} catch (IOException e) {
e.printStackTrace();
}
return addresses;
}
#Override
protected void onPostExecute(ArrayList<Address> addresses) {
if (addresses == null || addresses.size() == 0) {
Toast.makeText(getBaseContext(), "No Location found",
Toast.LENGTH_SHORT).show();
return;
}
// Clears all the existing markers on the map
googleMap.clear();
// Adding Markers on Google Map for each matching address
for (int i = 0; i < addresses.size(); i++) {
Address address = (Address) addresses.get(i);
// Creating an instance of GeoPoint, to display in Google Map
LatLng latLng;
latLng = new LatLng(address.getLatitude(),
address.getLongitude());
String addressText = String.format(
"%s, %s",
address.getMaxAddressLineIndex() > 0 ? address
.getAddressLine(0) : "", address
.getCountryName());
MarkerOptions markerOptions = new MarkerOptions();
// markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(addressText);
googleMap.addMarker(markerOptions);
// Locate the first location
if (i == 0)
googleMap.animateCamera(CameraUpdateFactory
.newLatLng(latLng));
}
}
}
class MapOverlay extends com.google.android.maps.Overlay {
#Override
public void draw(Canvas canvas, com.google.android.maps.MapView mapView,
boolean shadow) {
// TODO Auto-generated method stub
super.draw(canvas, mapView, shadow);
Point screenPts = new Point();
mapView.getProjection().toPixels(p, screenPts);
}
#Override
public boolean onTouchEvent(MotionEvent e,
com.google.android.maps.MapView mapView) {
// TODO Auto-generated method stub
if (e.getAction() == 1) {
com.google.android.maps.GeoPoint p = mapView.getProjection().fromPixels(
(int) e.getX(), (int) e.getY());
Toast.makeText(
getBaseContext(),
"Lat: " + p.getLatitudeE6() / 1E6 + ", Lon: "
+ p.getLongitudeE6() / 1E6, Toast.LENGTH_SHORT)
.show();
}
return false;
}
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
Add Activity into your manifest.xml because you need to give all path if your Activity located into different package.
<activity
android:name="com.mamun.tasktest.MapsActivity"
android:label="MapActivity" >
</activity>
And/or is your Activity belong to the same package then add simply
<activity android:name=".MapsActivity"></activity>
For more information go to:http://developer.android.com/guide/topics/manifest/manifest-intro.html
This is incorrect:
<activity android:name="MapsActivity"></activity>
You need to give full or relative path like this:
<activity android:name="com.mamun.tasktest.MapsActivity"></activity>
or
<activity android:name=".MapsActivity"></activity>
Replace your this tag in manifest
<activity android:name="MapsActivity"></activity>
by :
<activity android:name=".MapsActivity"></activity>
you should specify your full package name while declaring your activity into manifets.
See this link for reference:-
Add a new activity to the AndroidManifest?
You just forget to place a DOt (.) before MapsActivity. So, without that Dot (.) your class path looks like...
com.mamun.tasktestMapsActivity.java
But, it should be as....
com.mamun.tasktest.MapsActivity.java
Now, change this line of your Manifest...
<activity android:name="MapsActivity"></activity>
to...
<activity android:name=".MapsActivity"></activity>
I got the solution....The line "" should be inside application not inside directly on manifest.Like as below....
I've set up the http://bingmapsandroidsdk.codeplex.com/ to try bing maps instead of google maps on Android. Because I was unable to set that up.
I'm able to run Bing maps on my emulator but I'm unable to run it on my device(Galaxy S2).
I have a wifi connection on my phone but I'm still unable to get past the load screen.
I also checked this question but it doesn't solve the problem Working on Emulator but not on the real Android device
So my code:
Manifest
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.CALL_PHONE"/>
<uses-permission android:name="android.permission.ACCESS_GPS"></uses-permission>
<uses-sdk android:minSdkVersion="5" android:targetSdkVersion="15"/>
<application android:icon="#drawable/bingmaps_icon" android:label="#string/app_name" android:allowBackup="false">
<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>
<activity android:name="SplashActivity"></activity>
</application>
Starting Activity copied from the Bing-sdk
package org.bingmaps.app;
import java.util.HashMap;
import org.bingmaps.app.R;
import org.bingmaps.sdk.BingMapsView;
import org.bingmaps.sdk.Coordinate;
import org.bingmaps.sdk.EntityClickedListener;
import org.bingmaps.sdk.EntityLayer;
import org.bingmaps.sdk.MapLoadedListener;
import org.bingmaps.sdk.MapMovedListener;
import org.bingmaps.sdk.MapStyles;
import org.bingmaps.sdk.Pushpin;
import org.bingmaps.sdk.PushpinOptions;
import android.app.Activity;
import android.app.ProgressDialog;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ViewFlipper;
import android.widget.ZoomButton;
public class MainActivity extends Activity {
private BingMapsView bingMapsView;
private GPSManager _GPSManager;
private EntityLayer _gpsLayer;
private ProgressDialog _loadingScreen;
private Activity _baseActivity;
CharSequence[] _dataLayers;
boolean[] _dataLayerSelections;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
//OPTION Lock map orientation
setRequestedOrientation(1);
setContentView(R.layout.main);
Initialize();
}
private void Initialize()
{
_baseActivity = this;
_GPSManager = new GPSManager((Activity)this, new GPSLocationListener());
//Add more data layers here
_dataLayers = new String[] { getString(R.string.traffic)};
_dataLayerSelections = new boolean[ _dataLayers.length ];
_loadingScreen = new ProgressDialog(this);
_loadingScreen.setCancelable(false);
_loadingScreen.setMessage(this.getString(R.string.loading) + "...");
bingMapsView = (BingMapsView) findViewById(R.id.mapView);
//Create handler to switch out of Splash screen mode
final Handler viewHandler = new Handler() {
public void handleMessage(Message msg) {
((ViewFlipper) findViewById(R.id.flipper)).setDisplayedChild(1);
}
};
//Add a map loaded event handler
bingMapsView.setMapLoadedListener(new MapLoadedListener() {
public void onAvailableChecked() {
// hide splash screen and go to map
viewHandler.sendEmptyMessage(0);
//Add GPS layer
_gpsLayer = new EntityLayer(Constants.DataLayers.GPS);
bingMapsView.getLayerManager().addLayer(_gpsLayer);
UpdateGPSPin();
}
});
//Add a entity clicked event handler
bingMapsView.setEntityClickedListener(new EntityClickedListener() {
public void onAvailableChecked(String layerName, int entityId) {
HashMap<String, Object> metadata = bingMapsView.getLayerManager().GetMetadataByID(layerName, entityId);
DialogLauncher.LaunchEntityDetailsDialog(_baseActivity, metadata);
}
});
//Load the map
bingMapsView.loadMap(Constants.BingMapsKey, _GPSManager.GetCoordinate(), Constants.DefaultGPSZoomLevel, this.getString(R.string.mapCulture));
// Create zoom out button functionality
final ZoomButton zoomOutBtn = (ZoomButton) findViewById(R.id.zoomOutBtn);
zoomOutBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
bingMapsView.zoomOut();
}
});
// Create zoom button in functionality
final ZoomButton zoomInBtn = (ZoomButton) findViewById(R.id.zoomInBtn);
zoomInBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
bingMapsView.zoomIn();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.layout.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
//Map Mode menu items
case R.id.autoBtn:
bingMapsView.setMapStyle(MapStyles.Auto);
item.setChecked(!item.isChecked());
return true;
case R.id.roadBtn:
bingMapsView.setMapStyle(MapStyles.Road);
item.setChecked(!item.isChecked());
return true;
case R.id.aerialBtn:
bingMapsView.setMapStyle(MapStyles.Aerial);
item.setChecked(!item.isChecked());
return true;
case R.id.birdseyeBtn:
bingMapsView.setMapStyle(MapStyles.Birdseye);
item.setChecked(!item.isChecked());
return true;
//More option items
case R.id.aboutMenuBtn:
DialogLauncher.LaunchAboutDialog(this);
return true;
case R.id.layersMenuBtn:
DialogLauncher.LaunchLayersDialog(this, bingMapsView, _dataLayers, _dataLayerSelections);
return true;
case R.id.clearMapMenuBtn:
bingMapsView.getLayerManager().clearLayer(null);
//unselect all layers
for(int i=0;i<_dataLayerSelections.length;i++){
_dataLayerSelections[i] = false;
}
//re-add GPS layer
bingMapsView.getLayerManager().clearLayer(Constants.DataLayers.GPS);
UpdateGPSPin();
return true;
//GPS Menu Item
case R.id.gpsMenuBtn:
Coordinate coord = _GPSManager.GetCoordinate();
if(coord != null){
//Center on users GPS location
bingMapsView.setCenterAndZoom(coord, Constants.DefaultGPSZoomLevel);
}
return true;
//Search Menu Item
case R.id.searchMenuBtn:
DialogLauncher.LaunchSearchDialog(this, bingMapsView, loadingScreenHandler);
return true;
//Directions Menu Item
case R.id.directionsMenuBtn:
DialogLauncher.LaunchDirectionsDialog(this, bingMapsView, loadingScreenHandler);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void UpdateGPSPin(){
PushpinOptions opt = new PushpinOptions();
opt.Icon = Constants.PushpinIcons.GPS;
Pushpin p = new Pushpin(_GPSManager.GetCoordinate(), opt);
if (p.Location != null) {
_gpsLayer.clear();
_gpsLayer.add(p);
_gpsLayer.updateLayer();
}
}
#SuppressWarnings("unused")
private final MapMovedListener mapMovedListener = new MapMovedListener() {
public void onAvailableChecked() {
//OPTION Add logic to Update Layers here.
//This will update data layers when the map is moved.
}
};
/**
* Handler for loading Screen
*/
protected Handler loadingScreenHandler = new Handler() {
public void handleMessage(Message msg) {
if (msg.arg1 == 0) {
_loadingScreen.hide();
} else {
_loadingScreen.show();
}
}
};
public class GPSLocationListener implements LocationListener {
public void onLocationChanged(Location arg0) {
UpdateGPSPin();
}
public void onProviderDisabled(String arg0) {
}
public void onProviderEnabled(String arg0) {
}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
}
}
ERRORS from LOGCAT: non
bing maps for android does not work for android versions 3.0 and higher
I'm trying to make an app that will display an offline map with some clickable points on it.
My problem is that the map tiles won't show when i test my app. Plus the clickable points (markers) disappear as soon as i move the map.
Any help or ideas on the problem will be very helpful.
Here is my code:
MainActivity.java:
package com.cvasil05.offlinemapwithoverlay;
import java.util.ArrayList;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapController;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.MyLocationOverlay;
import org.osmdroid.views.overlay.OverlayItem;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends Activity {
// Default map zoom level:
private int MAP_DEFAULT_ZOOM = 17;
// Default map Latitude:
private double MAP_DEFAULT_LATITUDE = 35.14476619358656E6;
// Default map Longitude:
private double MAP_DEFAULT_LONGITUDE = 33.409520387649536E6;
private MapView mymapView = null;
private MapController myMapController = null;
private MyLocationOverlay location = null;
LocationManager mylocmanager = null;
LocationListener myloclistener = null;
ArrayList<OverlayItem> OverlayItemArray = null;
MyOverlayItem overlay = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize Map with its properties
mymapView = (MapView)findViewById(R.id.mapview);
mymapView.setBuiltInZoomControls(false);
mymapView.setMultiTouchControls(false);
mymapView.setTileSource(TileSourceFactory.MAPQUESTOSM);
// Initialize Map Controller
myMapController = mymapView.getController();
mylocmanager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
myloclistener = new LocationListener() {
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onLocationChanged(Location location) {
myMapController.animateTo(new GeoPoint(location.getLatitude(), location.getLongitude()));
myMapController.setZoom(17);
mymapView.invalidate();
}
public void run() {
// TODO Auto-generated method stub
location.runOnFirstFix(new Runnable() {
public void run() {
mymapView.getController().animateTo(location.getMyLocation());
}
});
}
};
mylocmanager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,0,myloclistener);
OverlayItemArray = new ArrayList<OverlayItem>();
// Points to be added
GeoPoint point1 = new GeoPoint(35.14392398396914E6, 33.40521812438965E6);
OverlayItem overlayitem1 = (OverlayItem) new OverlayItem("Εστίες", "Οι εστίες του Πανεπιστημίου Κύπρου.", point1);
OverlayItemArray.add(overlayitem1);
GeoPoint point2 = new GeoPoint(35.14447668501356E6, 33.41047525405884E6);
OverlayItem overlayitem2 = new OverlayItem("ΘΕΕ02", "Κτίριο Χημείας & Φυσικής.", point2);
OverlayItemArray.add(overlayitem2);
GeoPoint point3 = new GeoPoint(35.14461705293515E6, 33.41110825538635E6);
OverlayItem overlayitem3 = new OverlayItem("ΘΕΕ01", "Κτίριο Πληροφορικής & Μαθηματικών.", point3);
OverlayItemArray.add(overlayitem3);
GeoPoint point4 = new GeoPoint(35.14512588462148E6, 33.41071128845215E6);
OverlayItem overlayitem4 = new OverlayItem("ΧΩΔ01", "Χώροι Διδασκαλίας", point4);
OverlayItemArray.add(overlayitem4);
GeoPoint point5 = new GeoPoint(35.1459856274836E6, 33.41367244720459E6);
OverlayItem overlayitem5 = new OverlayItem("Κέντρο αθλητισμού", "Αποτελείται από το Γυμναστήριο, το Γήπεδο Τέννις και το Γύπεδο Φούτσαλ.", point5);
OverlayItemArray.add(overlayitem5);
// Add Points to Overlay
overlay = new MyOverlayItem(this, OverlayItemArray);
mymapView.getOverlays().add(overlay);
/*
// Get Location
location = new MyLocationOverlay(getApplicationContext(), mymapView);
// View Location
mymapView.getOverlays().add(location);
location.enableMyLocation();
location.disableFollowLocation();
*/
// Zoom and Center Map
myMapController.setZoom(MAP_DEFAULT_ZOOM);
myMapController.setCenter(new GeoPoint(MAP_DEFAULT_LATITUDE, MAP_DEFAULT_LONGITUDE));
}
// Create Menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
// Actions on Menu Options
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.esties){
myMapController.setZoom(MAP_DEFAULT_ZOOM);
myMapController.setCenter(new GeoPoint(MAP_DEFAULT_LATITUDE, MAP_DEFAULT_LONGITUDE));
}
return super.onOptionsItemSelected(item);
}
}
MyOverlayItem.java:
package com.cvasil05.offlinemapwithoverlay;
import java.util.List;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.ItemizedIconOverlay;
import org.osmdroid.views.overlay.OverlayItem;
import android.app.AlertDialog;
import android.content.Context;
public class MyOverlayItem extends ItemizedIconOverlay<OverlayItem> {
private Context mContext;
public MyOverlayItem(final Context context, final List<OverlayItem> aList) {
super(context, aList, new OnItemGestureListener<OverlayItem>() {
public boolean onItemSingleTapUp(final int index,
final OverlayItem item) {
return false;
}
public boolean onItemLongPress(final int index,
final OverlayItem item) {
return false;
}
});
// TODO Auto-generated constructor stub
mContext = context;
}
#Override
protected boolean onSingleTapUpHelper(final int index, final OverlayItem item, final MapView mapView) {
AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
dialog.setTitle(item.getTitle());
dialog.setMessage(item.getSnippet());
dialog.show();
return true;
}
}
my xml file has this:
<org.osmdroid.views.MapView
android:id="#+id/mapview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:enabled="true"
android:clickable="true"
/>
and i added this to my manifest file:
<supports-screens
android:anyDensity="true"
android:resizeable="false"
android:largeScreens="true"
android:normalScreens="true" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Im a newbe in osmdroid :) But I had the same Problem.. In my case my EmulatorDevice was configured with no SDCard
In Google Maps, I'm dropping a pin on user's current location but now I want to give another functionality to user that he can drag that pin manually and drop anywhere on the map, also by the time he drops the pin manually I can receive a callback which gives me the Longitude and Latitude of that position where user drops that pin.
If you can give me some examples it will be greatly appreciable.
In the last few days I finally found how to implement those functions you described and because there was no answer in this question, I decided to post what I found even though there has been a long time since you asked and you may found another answer by yourself.
So, I used the code of this git. I managed to do all that you want except the callback that I didn't try it in that way. I am getting the position of the pin after pressing a button.
There is no need to post my AndroidManifest because I read that you had no problem with displaying your location, so the permissions needed were fine.
The only thing that was required to do, was to create an activity named MapsActivity.
This is the whole content of it:
import com.google.android.gms.maps.*;
import com.google.android.gms.maps.model.*;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;
import common.logger.Log;
public class MapsActivity extends Activity implements
OnMapReadyCallback, GoogleMap.OnInfoWindowClickListener,
GoogleMap.OnMarkerDragListener {
LatLng position = new LatLng(34.6767, 33.04455);
final Marker marker_final = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.
map);
mapFragment.getMapAsync(this);
ImageButton returnback = (ImageButton)findViewById(R.id.returnback);
returnback.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MapsActivity.this.getApplicationContext(), position.latitude + ":" + position.longitude, Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onMapReady(GoogleMap map) {
map.setMyLocationEnabled(true);
map.moveCamera(CameraUpdateFactory.newLatLngZoom(position, 13));
CameraUpdate zoom = CameraUpdateFactory.zoomTo(15);
map.animateCamera(zoom);
map.addMarker(new MarkerOptions()
.title("Shop")
.snippet("Is this the right location?")
.position(position))
.setDraggable(true);
// map.setInfoWindowAdapter(new PopupAdapter(getLayoutInflater()));
map.setOnInfoWindowClickListener(this);
map.setOnMarkerDragListener(this);
}
#Override
public void onInfoWindowClick(Marker marker) {
Toast.makeText(this, marker.getTitle(), Toast.LENGTH_LONG).show();
}
#Override
public void onMarkerDragStart(Marker marker) {
LatLng position0 = marker.getPosition();
Log.d(getClass().getSimpleName(), String.format("Drag from %f:%f",
position0.latitude,
position0.longitude));
}
#Override
public void onMarkerDrag(Marker marker) {
LatLng position0 = marker.getPosition();
Log.d(getClass().getSimpleName(),
String.format("Dragging to %f:%f", position0.latitude,
position0.longitude));
}
#Override
public void onMarkerDragEnd(Marker marker) {
position = marker.getPosition();
Log.d(getClass().getSimpleName(), String.format("Dragged to %f:%f",
position.latitude,
position.longitude));
}
}
This is my activity_maps.xml layout (I've also added an edit text, but there is no need to use it):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:descendantFocusability="beforeDescendants"
android:focusableInTouchMode="true"
android:background="#ecf0f1">
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/scrollView3" >
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:weightSum="1"
android:layout_height="wrap_content">
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.9"
android:id="#+id/locationsearch" />
<ImageButton
android:layout_width="40dp"
android:layout_height="40dp"
android:id="#+id/search"
android:layout_weight="0.1"
android:background="#drawable/search" />
</LinearLayout>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="405dp"
android:name="com.google.android.gms.maps.MapFragment"/>
<ImageButton
android:layout_width="60dp"
android:layout_height="60dp"
android:id="#+id/returnback"
android:background="#drawable/less" />
</LinearLayout>
</ScrollView>
</LinearLayout>
Refer Below links where you can find samples from Commons guy
Sample
SO question
Hi Use the below code.
you will get the dropped pin position.
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
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;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;
public class rescue extends MapActivity {
private LocationManager myLocationManager;
private LocationListener myLocationListener;
private MapView myMapView;
private MapController myMapController;
private String provider;
private MyLocationOverlay me=null;
private int defaultLat =(int)(51.51216124955517);
private int defaultLong =(int)(-0.1373291015625);
private GeoPoint defaultGeoPint = new GeoPoint(defaultLat,defaultLong);
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rescue);
setCurrentLocation();
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
private void setCurrentLocation()
{
myMapView = (MapView)findViewById(R.id.rescueMapView);
myMapView.setTraffic(true);
///myMapView.setBuiltInZoomControls(true);
myMapController = myMapView.getController();
myMapController.setZoom(16); //Fixed Zoom Level
myLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
myLocationListener = new MyLocationListener();
try
{
Criteria criteria = new Criteria();
provider = myLocationManager.getBestProvider(criteria, false);
Location location = myLocationManager.getLastKnownLocation(provider);
myLocationManager.requestLocationUpdates(
provider,
0,
0,
myLocationListener);
Location lastLocation = myLocationManager.getLastKnownLocation(provider);
if(lastLocation != null)
{
int lastLocLat =(int)(lastLocation.getLatitude()*1000000);
int lastLocLong =(int)(lastLocation.getLongitude()*1000000);
//Get the current location in start-up
GeoPoint initGeoPoint = new GeoPoint(lastLocLat,lastLocLong);
CenterLocatio(initGeoPoint);
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Location Services Disabled")
.setMessage("The location service on the device are disabled, your location is not able to be found, please call AXA uding the button below to be rescued")
.setCancelable(false)
.setPositiveButton("Drop pin", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//do things
CenterLocatio(defaultGeoPint);
}
});
builder.create().show();
}
}
catch (Exception e)
{
// TODO: handle exception
Context context = getApplicationContext();
String toasttext = e.getMessage();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, toasttext, duration);
toast.show();
}
}
private void CenterLocatio(GeoPoint centerGeoPoint)
{
myMapView.getOverlays().clear();
myMapController.animateTo(centerGeoPoint);
Drawable marker=getResources().getDrawable(R.drawable.marker);
marker.setBounds(0, 0, marker.getIntrinsicWidth(),
marker.getIntrinsicHeight());
int lat = centerGeoPoint.getLatitudeE6();
int lon = centerGeoPoint.getLongitudeE6();
double lat1 = centerGeoPoint.getLatitudeE6()/1E6;
double lon1 = centerGeoPoint.getLongitudeE6()/1E6;
ArrayList<Double> passing = new ArrayList<Double>();
passing.add(lat1);
passing.add(lon1);
Context context = getApplicationContext();
ReverseGeocodeLookupTask task = new ReverseGeocodeLookupTask();
task.applicationContext = context;
task.activityContext = rescue.this;
task.execute(passing);
myMapView.getOverlays().add(new SitesOverlay(marker,lat, lon ));
me=new MyLocationOverlay(this, myMapView);
myMapView.getOverlays().add(me);
};
private class MyLocationListener implements LocationListener{
#Override
public void onLocationChanged(Location argLocation) {
// TODO Auto-generated method stub
GeoPoint myGeoPoint = new GeoPoint(
(int)(argLocation.getLatitude()*1000000),
(int)(argLocation.getLongitude()*1000000));
//CenterLocatio(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
}
}
private GeoPoint getPoint(int lat, int lon) {
return(new GeoPoint(lat, lon));
/*
return(new GeoPoint((int)(lat*1000000.0),
(int)(lon*1000000.0)));
*/
}
private class SitesOverlay extends ItemizedOverlay<OverlayItem> {
private List<OverlayItem> items=new ArrayList<OverlayItem>();
private Drawable marker=null;
private OverlayItem inDrag=null;
private ImageView dragImage=null;
private int xDragImageOffset=0;
private int yDragImageOffset=0;
private int xDragTouchOffset=0;
private int yDragTouchOffset=0;
public SitesOverlay(Drawable marker, int lat, int longitude) {
super(marker);
this.marker=marker;
dragImage=(ImageView)findViewById(R.id.drag);
xDragImageOffset=dragImage.getDrawable().getIntrinsicWidth()/2;
yDragImageOffset=dragImage.getDrawable().getIntrinsicHeight();
items.add(new OverlayItem(getPoint(lat,
longitude),
"UN", "United Nations"));
/*
items.add(new OverlayItem(getPoint(40.76866299974387,
-73.98268461227417),
"Lincoln Center",
"Home of Jazz at Lincoln Center"));
*/
populate();
}
#Override
protected OverlayItem createItem(int i) {
return(items.get(i));
}
#Override
public void draw(Canvas canvas, MapView mapView,
boolean shadow) {
super.draw(canvas, mapView, shadow);
boundCenterBottom(marker);
}
#Override
public int size() {
return(items.size());
}
#Override
public boolean onTouchEvent(MotionEvent event, MapView mapView) {
final int action=event.getAction();
final int x=(int)event.getX();
final int y=(int)event.getY();
boolean result=false;
if (action==MotionEvent.ACTION_DOWN) {
for (OverlayItem item : items) {
Point p=new Point(0,0);
myMapView.getProjection().toPixels(item.getPoint(), p);
if (hitTest(item, marker, x-p.x, y-p.y)) {
result=true;
inDrag=item;
items.remove(inDrag);
populate();
xDragTouchOffset=0;
yDragTouchOffset=0;
setDragImagePosition(p.x, p.y);
dragImage.setVisibility(View.VISIBLE);
xDragTouchOffset=x-p.x;
yDragTouchOffset=y-p.y;
break;
}
}
}
else if (action==MotionEvent.ACTION_MOVE && inDrag!=null) {
setDragImagePosition(x, y);
result=true;
}
else if (action==MotionEvent.ACTION_UP && inDrag!=null) {
dragImage.setVisibility(View.GONE);
GeoPoint pt=myMapView.getProjection().fromPixels(x-xDragTouchOffset,
y-yDragTouchOffset);
String title = inDrag.getTitle();
OverlayItem toDrop=new OverlayItem(pt, title,
inDrag.getSnippet());
items.add(toDrop);
populate();
double lat = pt.getLatitudeE6()/1E6;
double lon = pt.getLongitudeE6()/1E6;
ArrayList<Double> passing = new ArrayList<Double>();
passing.add(lat);
passing.add(lon);
Context context = getApplicationContext();
ReverseGeocodeLookupTask task = new ReverseGeocodeLookupTask();
task.applicationContext = context;
task.activityContext = rescue.this;
task.execute(passing);
//CenterLocatio(pt);
inDrag=null;
result=true;
}
return(result || super.onTouchEvent(event, mapView));
}
private void setDragImagePosition(int x, int y) {
RelativeLayout.LayoutParams lp=
(RelativeLayout.LayoutParams)dragImage.getLayoutParams();
lp.setMargins(x-xDragImageOffset-xDragTouchOffset,
y-yDragImageOffset-yDragTouchOffset, 0, 0);
dragImage.setLayoutParams(lp);
}
}
public class ReverseGeocodeLookupTask extends AsyncTask <ArrayList<Double>, Void, String>
{
private ProgressDialog dialog;
protected Context applicationContext;
protected Context activityContext;
#Override
protected void onPreExecute()
{
this.dialog = ProgressDialog.show(activityContext, "Please wait",
"Requesting location", true);
}
protected String doInBackground(ArrayList<Double>... params)
{
String foundAddress = "";
String localityName = "";
ArrayList<Double> passed = params[0];
double lat = passed.get(0);
double lon = passed.get(1);
try
{
List<Address> addresses = new Geocoder(applicationContext,Locale.getDefault()).getFromLocation(lat,lon, 1);
if (addresses.size() > 0)
{
String addressLine = "";
for(Integer i = 0; i < addresses.get(0).getMaxAddressLineIndex(); i++)
{
if(!addressLine.equals(""))
{
addressLine+= ", ";
}
addressLine+= addresses.get(0).getAddressLine(i);
}
if(addressLine!="")
{
foundAddress+= addressLine;
}
}
}
catch (Exception e) {
// TODO: handle exception
}
finally
{
}
return foundAddress;
}
#Override
protected void onPostExecute(String result)
{
this.dialog.cancel();
showToast(result);
}
}
public void showToast(String message)
{
Context context = getApplicationContext();
String toasttext = message;
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, toasttext, duration);
toast.show();
}
}
Use below permission in manifest file
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<uses-library android:name="com.google.android.maps" />
<activity
android:label="#string/app_name"
android:name=".DragAndDropPinActivity" >
</activity>
<activity
android:label="#string/app_name"
android:name=".rescue" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
The code shows below what i have done till now. Now what i need to do is, when i send an sms to the person i get his location back and that too i want to show the location on google map!!
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mehul.googlemaps"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<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"/>
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name">
<uses-library android:name="com.google.android.maps" />
<activity
android:name=".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>
<activity android:name=".HelloWorld" />
</application>
</manifest>
Main.java
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class Main extends MapActivity implements LocationListener {
/** Called when the activity is first created. */
MapView map;
long start;
long stop;
int x, y;
GeoPoint touchedPoint;
Drawable d;
List<Overlay> overlayList;
LocationManager lm;
String towers;
int lat ;
int longi;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button)findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(Main.this, HelloWorld.class);
startActivity(intent);
}
});
map = (MapView)findViewById(R.id.mv);
map.setBuiltInZoomControls(true);
Touchy t = new Touchy();
overlayList = map.getOverlays();
overlayList.add(t);
d = getResources().getDrawable(R.drawable.pinn);
//Placing pintpoint
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria crit = new Criteria();
towers = lm.getBestProvider(crit, false);
Location location = lm.getLastKnownLocation(towers);
if (location != null){
lat = (int) (location.getLatitude() *1E6);
longi= (int) (location.getLongitude() *1E6);
GeoPoint ourLocation = new GeoPoint(lat,longi);
OverlayItem overlayItem = new OverlayItem(ourLocation, "Hi!!", "2nd");
CustomPinPoint custom = new CustomPinPoint(d, Main.this);
custom.insertPinpoint(overlayItem);
overlayList.add(custom);
}else{
Toast.makeText(Main.this, "Couldnt get provider", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
lm.removeUpdates(this);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
lm.requestLocationUpdates(towers, 500, 1, this );
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
class Touchy extends Overlay{
public boolean onTouchEvent(MotionEvent e, MapView m){
if (e.getAction() == MotionEvent.ACTION_DOWN){
start = e.getEventTime();
}
if (e.getAction() == MotionEvent.ACTION_UP){
stop = e.getEventTime();
x = (int) e.getX();
y = (int) e.getY();
touchedPoint = map.getProjection().fromPixels(x, y);
}
if (stop - start > 1500){
AlertDialog alert = new AlertDialog.Builder(Main.this).create();
alert.setTitle("Pick Option");
alert.setButton("Hello", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
OverlayItem overlayItem = new OverlayItem(touchedPoint, "Hi!!", "2nd");
CustomPinPoint custom = new CustomPinPoint(d, Main.this);
custom.insertPinpoint(overlayItem);
overlayList.add(custom);
}
});
alert.setButton3("Get Address", new DialogInterface.OnClickListener() {
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.setButton2("Toggle View", new DialogInterface.OnClickListener() {
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.setButton("Place a Pin", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
OverlayItem overlayItem = new OverlayItem(touchedPoint, "Hi!!", "2nd");
CustomPinPoint custom = new CustomPinPoint(d, Main.this);
custom.insertPinpoint(overlayItem);
overlayList.add(custom);
}
});
alert.show();
return true;
}
return false;
}
}
public void onLocationChanged(Location l) {
// TODO Auto-generated method stub
lat = (int) (l.getLatitude() *1E6);
longi = (int) (l.getLongitude() *1E6);
GeoPoint ourLocation = new GeoPoint(lat,longi);
OverlayItem overlayItem = new OverlayItem(ourLocation, "Hi!!", "2nd");
CustomPinPoint custom = new CustomPinPoint(d, Main.this);
custom.insertPinpoint(overlayItem);
overlayList.add(custom);
}
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
}
}
Helloworld.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
public class HelloWorld extends Activity
{
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.helloworld);
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.putExtra("sms_body", "Content of the SMS goes here...");
sendIntent.setType("vnd.android-dir/mms-sms");
startActivity(sendIntent);
}
}
If anything else is required let me know.
Assuming the other person will also have your app installed, you could create a BroadcastReceiverwhich would respond to the android.provider.Telephony.SMS_RECEIVED action. The receiver should implement onReceive, detect if the message originated from your application (use some special key in the message body i guess?), extract the message and originating phone number from the extras in the received Intent, then trigger a location listener which would then send an SMS back...
The same BroadcastReceiver could also detect if the message has latitude/longitude in it, store the coordinates in some persistent storage, and send a broadcast intent to tell your MapActivity to update it's map with the new coordinates...