This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
How to put JSON lOutput (latitude and longitude) on the map
I have a main activity which parses the JSON data from my mysql (table tracking:Lattitude and longitude) Now I want to pass this data in to my MapActivity and display on google maps. Any help is highly appreciated. Thanks!
this my JSONactivity
public class JSONActivity extends Activity{
private JSONObject jObject;
private String xResult ="";
//Seusuaikan url dengan nama domain
private String url = "http://10.0.2.2/labiltrack/daftartracking.php";
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.daftartrack);
TextView txtResult = (TextView)findViewById(R.id.TextViewResult);
//url += "?lattitude=" + UserData.getEmail();
xResult = getRequest(url);
try {
parse(txtResult);
} catch (Exception e) {
e.printStackTrace();
}
}
private void parse(TextView txtResult) throws Exception {
// TODO Auto-generated method stub
jObject = new JSONObject(xResult);
JSONArray menuitemArray = jObject.getJSONArray("joel");
String sret="";
//int j = 0;
for (int i = 0; i < menuitemArray.length(); i++) {
sret +=menuitemArray.getJSONObject(i).
getString("lattitude").toString()+" : ";
System.out.println(menuitemArray.getJSONObject(i)
.getString("lattitude").toString());
System.out.println(menuitemArray.getJSONObject(i).getString(
"longitude").toString());
sret +=menuitemArray.getJSONObject(i).getString(
"lattitude").toString()+"\n";
//j=i;
}txtResult.setText(sret);
}
/**
* Method untuk Mengirimkan data keserver
* event by button login diklik
*
* #param view
*/
private String getRequest(String url) {
// TODO Auto-generated method stub
String sret="";
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
try{
HttpResponse response = client.execute(request);
sret =request(response);
}catch(Exception ex){
Toast.makeText(this,"jo "+sret, Toast.LENGTH_SHORT).show();
}
return sret;
}
/**
* Method untuk Menenrima data dari server
* #param response
* #return
*/
private String request(HttpResponse response) {
// TODO Auto-generated method stub
String result = "";
try{
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
str.append(line + "\n");
}
in.close();
result = str.toString();
}catch(Exception ex){
result = "Error";
}
return result;
}
}
and this my mapActivity
public class mapactivity extends MapActivity {
private MapView mapView;
MapController mc;
GeoPoint p;
//private MyLocationOverlay me = null;
class MapOverlays extends com.google.android.maps.Overlay
{
#Override
public boolean draw (Canvas canvas, MapView mapView, boolean shadow, long when)
{
super.draw(canvas, mapView, shadow);
//translate the geopoint to screen pixels
Point screenPts = new Point();
mapView.getProjection().toPixels(p, screenPts);
//tambah marker
Bitmap bmp = BitmapFactory.decodeResource(getResources (), R.drawable.pin_red);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y-50, null);
//mapView.setSatellite(true);
return true;
}
#Override
public boolean onTouchEvent(MotionEvent event, MapView mapView)
{
//---when user lifts his finger---
if (event.getAction() == 1) {
GeoPoint p = mapView.getProjection().fromPixels(
(int) event.getX(),
(int) event.getY());
Toast.makeText(getBaseContext(),
p.getLatitudeE6() / 1E6 + "," +
p.getLongitudeE6() /1E6 ,
Toast.LENGTH_SHORT).show();
mc.animateTo(p);
//geocoding
Geocoder geoCoder = new Geocoder(
getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(
p.getLatitudeE6() / 1E6,
p.getLongitudeE6() / 1E6, 1);
String add = "";
if (addresses.size() > 0)
{
for (int i=0; i<addresses.get(0).getMaxAddressLineIndex();
i++)
add += addresses.get(0).getAddressLine(i) + "\n";
}
Toast.makeText(getBaseContext(), add, Toast.LENGTH_SHORT).show();
}
catch (IOException e) {
e.printStackTrace();
}
return true;
}
else
return false;
} }
/** Called when the activity is first created. */
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mapview1);
//utk mnampilkan zoom
mapView = (MapView) findViewById(R.id.mapView);
LinearLayout zoomLayout = (LinearLayout)findViewById(R.id.zoom);
View zoomView = mapView.getZoomControls();
zoomLayout.addView(zoomView,
new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
mapView.displayZoomControls(true);
//menampilkan default peta banda aceh
mc = mapView.getController();
String coordinates[] = {"5.550381", "95.318699"};
double lat = Double.parseDouble(coordinates[0]);
double lng = Double.parseDouble(coordinates[1]);
p = new GeoPoint(
(int) (lat * 1E6),
(int) (lng * 1E6));
mc.animateTo(p);
mc.setZoom(14);
mapView.invalidate();
//tambah marker
MapOverlays mapOverlay = new MapOverlays();
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
mapView.invalidate();
}
public void btnSatelitClick(View v){
mapView.setSatellite(true);
mapView.setStreetView(false);
}
public void btnjalanClick (View v){
mapView.setSatellite(false);
mapView.setStreetView(true);
}
protected boolean isRouteDisplayed()
{
//auto generate method
return false;
}
}
as you have only to variable to pass so use intent and pass the data ......and i think you have rest of code writen
put in the JSONActivity from where you want to open mapActivity and you alos have the variable latitude and longitude with their values
Intent i= new Intent(getApplicationContext(), mapActivity.class);
i.putExtra("lattitude",lattitude);
i.putExtra("longitude",longitude);
startActivity(i);
Then in the new activity mapActivity, retrieve those values:
inplace of this put String coordinates[] = {"5.550381", "95.318699"};
Bundle extras = getIntent().getExtras();
if(extras !=null) {
String lattitude= extras.getString("lattitude");
String longitude= extras.getString("longitude");
double lat = Double.parseDouble(lattitude);
double lng = Double.parseDouble(longitude);
}
Related
I'm trying to set routes directions in my app using google API v2 but I'm getting this error that I can't find what is causing the problem
D/Exception while reading url﹕ java.io.FileNotFoundException: https://maps.googleapis.com/maps/api/directions/json?waypoints=optimize:true|-23.3246,-51.1489|-23.3206,-51.1459|-23.2975,-51.2007&sensor=false
And when I copy and paste that link on Chrome I get the following:
"error_message" : "Invalid request. Missing the 'origin' parameter.",
This is my map Class:
public class MapaViagem extends FragmentActivity {
private GoogleMap googleMap;
private String IdViagem;
private List<EnderecoModel> mEnderecoModel = new ArrayList<EnderecoModel>();
private ArrayList<LatLng> coordList = new ArrayList<LatLng>();
private ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
setContentView(R.layout.maps);
// Loading map
initilizeMap();
// Changing map type
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
// googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
// googleMap.setMapType(GoogleMap.MAP_TYPE_NONE);
// Showing / hiding your current location
googleMap.setMyLocationEnabled(true);
// Enable / Disable zooming controls
googleMap.getUiSettings().setZoomControlsEnabled(true);
// Enable / Disable my location button
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
// Enable / Disable Compass icon
googleMap.getUiSettings().setCompassEnabled(true);
// Enable / Disable Rotate gesture
googleMap.getUiSettings().setRotateGesturesEnabled(true);
// Enable / Disable zooming functionality
googleMap.getUiSettings().setZoomGesturesEnabled(true);
try {
Bundle parametros = getIntent().getExtras();
IdViagem = parametros.getString("id_viagem");
Repositorio mRepositorio = new Repositorio(this);
String waypoints = "waypoints=optimize:true";
String coordenadas = "";
mEnderecoModel = mRepositorio.getListaEnderecosDaViagem(Integer.valueOf(IdViagem));
for (int j = 0; j < mEnderecoModel.size(); j++) {
float latitude = Float.parseFloat(mEnderecoModel.get(j).getLatitude());
float longitude = Float.parseFloat(mEnderecoModel.get(j).getLongitude());
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 10));
coordenadas += "|" + latitude + "," + longitude;
coordList.add(new LatLng(latitude, longitude));
// Creating MarkerOptions
MarkerOptions options = new MarkerOptions();
// Setting the position of the marker
options.position(new LatLng(latitude, longitude));
if (j == mEnderecoModel.size() - 1) {
options.icon(BitmapDescriptorFactory.fromBitmap(writeTextOnDrawable(R.drawable.vermelho, String.valueOf(mEnderecoModel.size()))));
} else {
options.icon(BitmapDescriptorFactory.fromBitmap(writeTextOnDrawable(R.drawable.verde, String.valueOf(j + 1))));
}
// Add new marker to the Google Map Android API V2
googleMap.addMarker(options);
}
String sensor = "sensor=false";
String params = waypoints + coordenadas + "&" + sensor;
String url = "https://maps.googleapis.com/maps/api/directions/json?" + params;
ReadTask downloadTask = new ReadTask();
downloadTask.execute(url);
} catch (Exception e) {
e.printStackTrace();
}
}
private class ReadTask extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(MapaViagem.this);
// setup your dialog here
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setTitle("Traçando Rotas");
dialog.setMessage("Aguarde...");
dialog.setCancelable(false);
dialog.show();
}
#Override
protected String doInBackground(String... url) {
String data = "";
try {
HttpConnection http = new HttpConnection();
data = http.readUrl(url[0]);
} catch (Exception e) {
e.printStackTrace();
}
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
new ParserTask().execute(result);
}
}
private class ParserTask extends
AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {
#Override
protected List<List<HashMap<String, String>>> doInBackground(
String... jsonData) {
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try {
jObject = new JSONObject(jsonData[0]);
PathJSONParser parser = new PathJSONParser();
routes = parser.parse(jObject);
} catch (Exception e) {
e.printStackTrace();
}
return routes;
}
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> routes) {
ArrayList<LatLng> points = null;
PolylineOptions polyLineOptions = null;
if(routes != null){
for (int i = 0; i < routes.size(); i++) {
points = new ArrayList<LatLng>();
polyLineOptions = new PolylineOptions();
List<HashMap<String, String>> path = routes.get(i);
for (int j = 0; j < path.size(); j++) {
HashMap<String, String> point = path.get(j);
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
polyLineOptions.addAll(points);
polyLineOptions.width(4);
polyLineOptions.color(Color.BLUE);
}
googleMap.addPolyline(polyLineOptions);
}
if (dialog.isShowing()) {
dialog.dismiss();
}
}
}
private Bitmap writeTextOnDrawable(int drawableId, String text) {
Bitmap bm = BitmapFactory.decodeResource(getResources(), drawableId)
.copy(Bitmap.Config.ARGB_8888, true);
Typeface tf = Typeface.create("Helvetica", Typeface.BOLD);
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.WHITE);
paint.setTypeface(tf);
paint.setTextAlign(Paint.Align.CENTER);
paint.setTextSize(convertToPixels(MapaViagem.this, 11));
Rect textRect = new Rect();
paint.getTextBounds(text, 0, text.length(), textRect);
Canvas canvas = new Canvas(bm);
//If the text is bigger than the canvas , reduce the font size
if (textRect.width() >= (canvas.getWidth() - 4)) //the padding on either sides is considered as 4, so as to appropriately fit in the text
paint.setTextSize(convertToPixels(MapaViagem.this, 7)); //Scaling needs to be used for different dpi's
//Calculate the positions
int xPos = (canvas.getWidth() / 2) - 1; //-2 is for regulating the x position offset
//"- ((paint.descent() + paint.ascent()) / 2)" is the distance from the baseline to the center.
int yPos = (int) ((canvas.getHeight() / 2) - ((paint.descent() + paint.ascent()) / 8f));
canvas.drawText(text, xPos, yPos, paint);
return bm;
}
public static int convertToPixels(Context context, int nDP) {
final float conversionScale = context.getResources().getDisplayMetrics().density;
return (int) ((nDP * conversionScale) + 0.5f);
}
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Não foi possível carregar o mapa", Toast.LENGTH_SHORT)
.show();
}
}
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public void onBackPressed() {
super.onBackPressed();
overridePendingTransition(R.anim.animation_back, R.anim.animation_back_leave);
finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_mapa, menu);
return super.onCreateOptionsMenu(menu);
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
super.onBackPressed();
overridePendingTransition(R.anim.animation_back, R.anim.animation_back_leave);
finish();
return true;
case R.id.menu_atualizar_mapa:
/* dispara os repositorios a sincronizar */
new Sincronizar(MapaViagem.this, MapaViagem.this).execute(0);
}
return true;
}
#Override
protected void onResume() {
super.onResume();
initilizeMap();
}
}
The url which is being generated in the code : "https://maps.googleapis.com/maps/api/directions/json?waypoints=optimize:true|-23.3246,-51.1489|-23.3206,-51.1459|-23.2975,-51.2007&sensor=false"
is WRONG.
Your URL should be like this : "https://maps.googleapis.com/maps/api/directions/json?origin=-23.3246,-51.1489&destination=-23.2975,-51.2007&%20waypoints=optimize:true|-23.3246,-51.1489|-23.3206,-51.1459|-23.2975,-51.2007&sensor=false"
Here's the code to generate the url :
private String getMapsApiDirectionsUrl(LatLng Office, LatLng home) {
String waypoints = "waypoints=optimize:true|"
+ Office.latitude + "," + Office.longitude
+ "|" + "|" + home.latitude + ","
+ home.longitude;
String OriDest = "origin="+Office.latitude+","+Office.longitude+"&destination="+home.latitude+","+home.longitude;
String sensor = "sensor=false";
String params = OriDest+"&%20"+waypoints + "&" + sensor;
String output = "json";
String url = "https://maps.googleapis.com/maps/api/directions/"
+ output + "?" + params;
return url;
}
I'm trying to create and show route between the device current location and a defined point.
I use this code:
public class RoutePath extends MapActivity {
/** Called when the activity is first created. */
MapView mapView;
private RoutePath _activity;
GeoPoint srcGeoPoint,destGeoPoint;
private static List<Overlay> mOverlays;
MapController mc;
Location location;
private MyLocationOverlay myLocationOverlay;
String n;
double longitude;
double latitude;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedData data = SharedData.getInstance();
mapView = new MapView(this,"apyKey");
mapView.setClickable(true);
setContentView(mapView);
_activity = this;
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location =lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
longitude = location.getLongitude();
latitude = location.getLatitude();
double src_lat = latitude;
double src_long = longitude;
double dest_lat = 38.1267303;
double dest_long = 13.3466097;
String n = String.valueOf(src_long);
Log.d("asd",n);
if(src_lat == -1 || src_long == -1 || dest_lat == -1 || dest_long == -1){
showAlert("Please enter source and destination points");
}else{
srcGeoPoint = new GeoPoint((int) (src_lat * 1E6),(int) (src_long * 1E6));
destGeoPoint = new GeoPoint((int) (dest_lat * 1E6),(int) (dest_long * 1E6));
List<Overlay> mapOverlays = mapView.getOverlays();
Drawable srcdrawable = this.getResources().getDrawable(R.drawable.pushpin1);
CustomItemizedOverlay srcitemizedOverlay = new CustomItemizedOverlay(srcdrawable);
//CustomItemizedOverlay srcitemizedOverlay = new CustomItemizedOverlay(getDrawable("com/agarwal/route/pin_green.png"));
OverlayItem srcoverlayitem = new OverlayItem(srcGeoPoint, "Hello!", "This is your Location.");
Drawable destdrawable = this.getResources().getDrawable(R.drawable.pushpin1);
CustomItemizedOverlay destitemizedOverlay = new CustomItemizedOverlay( destdrawable );
// CustomItemizedOverlay destitemizedOverlay = new CustomItemizedOverlay(getDrawable("com/agarwal/route/pin_red.png"));
OverlayItem destoverlayitem = new OverlayItem(destGeoPoint, "Hello!", "This is dest Location.");
srcitemizedOverlay.addOverlay(srcoverlayitem);
destitemizedOverlay.addOverlay(destoverlayitem);
mapOverlays.add(srcitemizedOverlay);
mapOverlays.add(destitemizedOverlay);
connectAsyncTask _connectAsyncTask = new connectAsyncTask();
_connectAsyncTask.execute();
mapView.setBuiltInZoomControls(true);
mapView.displayZoomControls(true);
mOverlays = mapView.getOverlays();
mapView.getController().animateTo(srcGeoPoint);
mapView.getController().setZoom(12);
}
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
//era private prima di
private class connectAsyncTask extends AsyncTask<Void, Void, Void>{
private ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog = new ProgressDialog(_activity);
progressDialog.setMessage("Caricamento del percorso...");
progressDialog.setIndeterminate(true);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
fetchData();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(doc!=null){
Overlay ol = new MyOverlay(_activity,srcGeoPoint,srcGeoPoint,1);
mOverlays.add(ol);
NodeList _nodelist = doc.getElementsByTagName("status");
Node node1 = _nodelist.item(0);
String _status1 = node1.getChildNodes().item(0).getNodeValue();
if(_status1.equalsIgnoreCase("OK")){
NodeList _nodelist_path = doc.getElementsByTagName("overview_polyline");
Node node_path = _nodelist_path.item(0);
Element _status_path = (Element)node_path;
NodeList _nodelist_destination_path = _status_path.getElementsByTagName("points");
Node _nodelist_dest = _nodelist_destination_path.item(0);
String _path = _nodelist_dest.getChildNodes().item(0).getNodeValue();
List<GeoPoint> _geopoints = decodePoly(_path);
GeoPoint gp1;
GeoPoint gp2;
gp2 = _geopoints.get(0);
Log.d("_geopoints","::"+_geopoints.size());
for(int i=1;i<_geopoints.size();i++) // the last one would be crash
{
gp1 = gp2;
gp2 = _geopoints.get(i);
Overlay ol1 = new MyOverlay(gp1,gp2,2,Color.BLUE);
mOverlays.add(ol1);
}
Overlay ol2 = new MyOverlay(_activity,destGeoPoint,destGeoPoint,3);
mOverlays.add(ol2);
progressDialog.dismiss();
}else{
showAlert("Unable to find the route");
}
Overlay ol2 = new MyOverlay(_activity,destGeoPoint,destGeoPoint,3);
mOverlays.add(ol2);
progressDialog.dismiss();
mapView.scrollBy(-1,-1);
mapView.scrollBy(1,1);
}else{
showAlert("Unable to find the route");
}
}
} //end Async
Document doc = null;
private void fetchData()
{
StringBuilder urlString = new StringBuilder();
urlString.append("http://maps.google.com/maps/api/directions/xml?origin=");
urlString.append( Double.toString((double)srcGeoPoint.getLatitudeE6()/1.0E6 ));
urlString.append(",");
urlString.append( Double.toString((double)srcGeoPoint.getLongitudeE6()/1.0E6 ));
urlString.append("&destination=");//to
urlString.append( Double.toString((double)destGeoPoint.getLatitudeE6()/1.0E6 ));
urlString.append(",");
urlString.append( Double.toString((double)destGeoPoint.getLongitudeE6()/1.0E6 ));
urlString.append("&sensor=true&mode=driving");
Log.d("url","::"+urlString.toString());
HttpURLConnection urlConnection= null;
URL url = null;
try
{
url = new URL(urlString.toString());
urlConnection=(HttpURLConnection)url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.connect();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
doc = (Document) db.parse(urlConnection.getInputStream());//Util.XMLfromString(response);
}catch (MalformedURLException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}catch (ParserConfigurationException e){
e.printStackTrace();
}
catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private List<GeoPoint> decodePoly(String encoded) {
List<GeoPoint> poly = new ArrayList<GeoPoint>();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
GeoPoint p = new GeoPoint((int) (((double) lat / 1E5) * 1E6),
(int) (((double) lng / 1E5) * 1E6));
poly.add(p);
}
return poly;
}
private void showAlert(String message){
AlertDialog.Builder alert = new AlertDialog.Builder(_activity);
alert.setTitle("Error");
alert.setCancelable(false);
alert.setMessage(message);
alert.setPositiveButton("Ok",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
alert.show();
}
private Drawable getDrawable(String fileName){
return Drawable.createFromStream(_activity.getClass().getClassLoader().getResourceAsStream(fileName), "pin");
}
}
This is for an application for smartphone Galaxy Nexus, android 4.2 .
I tested it on my tablet, android 4.0.2, and it works well.
But when i test it on the smartphone, it crashes.
I tried to change LocationManager.NETWORK_PROVIDER with LocationManager.GPS_PROVIDER but it crashes anyway. I can't solve this problem. Can anyone help me?
I struggled with the identical problems for several hours. The same piece of code works fine on my Android 2.7 device, but just not work for my Android 4.1.1. Eventually, I found out that, for some reasons, getLastKnownLocation() does not work if requestLocationUpdates() is not called first.
As a result, my LocationListener starts to update after I put these two lines:
locationManager.requestLocationUpdates(provider, 1000, 10, locationListener);
Location location = locationManager.getLastKnownLocation(provider);
Hope it helps.
Have you given appropriate permissions in the manifest file
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
Check the Android dev doc here
Any chance your getting a null pointer.
Your getting the location from getLastKnownLocation() and then using this object without checking if it's null. getLastKnownLocation can return null if there is no known location.
I've been trying to add my GeoPoints to the itemizedOverlay Array in order to draw the points on the map. Unfortunately, the app crashing at this point.
My Code:
package com.example.phooogle;
public class GoogleMapsAppActivity extends MapActivity {
private MapView mapView;
private MapController mc;
private MyLocationOverlay myLocationOverlay;
private myMapService mms;
String[] ms;
private LocationManager lm;
private LocationListener locationListener;
private MyLocationOverlay myLocOverlay;
GeoPoint p;
GeoPoint progress1[];
List<GeoPoint> geoPointsArray = new ArrayList<GeoPoint>();
int latitude;
int longitude;
private ProgressDialog progress;
MotionEvent event;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cool_map);
progress= new ProgressDialog(this);
progress.setIndeterminate(true);
progress.setMessage("I am thinking");
InitTask init_task= new InitTask();
init_task.execute("144.963620993985", "-37.8140023779914", "20", "Litter Bin");
try {
String[] arrs = init_task.strArr2;
//Log.d(" print points", " Array Size " + arrs.length);
Drawable makerDefault = this.getResources().getDrawable(R.drawable.poke);
MirItemizedOverlay itemizedOverlay = new MirItemizedOverlay(makerDefault);
for(int j=0; j<arrs.length ;j++)
{
double y =0;
double x =0;
if(j == 1)
{
/// x
//Log.d("Results", "2If statem " + strArr2[j] );
x = Double.parseDouble(arrs[j]);
y = Double.parseDouble(arrs[j+1]);
//Log.d(" print points", "lat " + x + " long" + y);
itemizedOverlay.addOverlayItem((int) x , (int) y , "La trobe");
mapView.getOverlays().add(itemizedOverlay );
}
}
MapController mc = mapView.getController();
mc.setCenter(new GeoPoint((int) (1E6 * -37.720754), (int) (1E6 * 145.048798))); // Some where .
mc.zoomToSpan(itemizedOverlay.getLatSpanE6(), itemizedOverlay.getLonSpanE6());
} finally {}
initMap();
initMyLocation();
// theRouteDraw();
/*
Drawable makerDefault = this.getResources().getDrawable(R.drawable.poke);
MirItemizedOverlay itemizedOverlay = new MirItemizedOverlay(makerDefault);
itemizedOverlay.addOverlayItem(init_task.geoPointsArray, "La trobe");
mapView.getOverlays().add(itemizedOverlay );
MapController mc = mapView.getController();
mc.setCenter(new GeoPoint((int) (1E6 * -37.720754), (int) (1E6 * 145.048798))); // Some where .
mc.zoomToSpan(itemizedOverlay.getLatSpanE6(), itemizedOverlay.getLonSpanE6());
for (int i = 0; i < geoPointsArray.size() ; i++)
{
Log.d(" print points", " points " + geoPointsArray.get(i));
}*/
// Log.d(" print points", " Size " + init_task.geoPointsArray.size());
/*
mapView = (MapView) findViewById(R.id.mapview);
List<Overlay> mapOverlays = mapView.getOverlays();
//add any icon here for the marker
Drawable drawable = GoogleMapsAppActivity.this.getResources().getDrawable(R.drawable.poke);
MapViewItemizedOverlay itemizedOverlay = new MapViewItemizedOverlay(drawable,this);
//use your array here instead
//GeoPoint point1 = new GeoPoint(lat,lng);
OverlayItem overlayitem1 = new OverlayItem(point1, "Info", "You are here!" );
itemizedOverlay.addOverlay(overlayitem1);
mapOverlays.add(itemizedOverlay);
*/
}
private void initMap()
{
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
// mapView.setStreetView(true);
mc = mapView.getController();
}
public void theRouteDraw(GeoPoint p){
mc.animateTo(p);
mc.setZoom(13);
mapView.invalidate();
mapView.setSatellite(true);
}
private void initMyLocation() {
myLocOverlay = new MyLocationOverlay(this, mapView);
myLocOverlay.enableMyLocation();
mapView.getOverlays().add(new myLocOverlay());
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
class myLocOverlay extends Overlay{
public void draw(Canvas canvas, MapView mapv, boolean shadow){
super.draw(canvas, mapv, shadow);
Projection projection = mapView.getProjection();
Path p1 = new Path();
for (int i = 0; i < geoPointsArray.size(); i++) {
if (i == geoPointsArray.size() - 1) {
break;
}
Point from = new Point();
Point to = new Point();
projection.toPixels(geoPointsArray.get(i), from);
projection.toPixels(geoPointsArray.get(i + 1), to);
p1.moveTo(from.x, from.y);
p1.lineTo(to.x, to.y);
}
Paint mPaint = new Paint();
mPaint.setStyle(Style.STROKE);
mPaint.setColor(Color.BLACK);
mPaint.setAntiAlias(true);
mPaint.setStrokeWidth(4);
canvas.drawPath(p1, mPaint);
super.draw(canvas, mapView, shadow);
}
}
private class InitTask extends AsyncTask<String, GeoPoint, List<GeoPoint>> {
List<GeoPoint> geoPointsArray = new ArrayList<GeoPoint>();
GeoPoint p;
private ProgressDialog progressDialog;
private String rst = " " ;
private String[] strArr1;
private String[] strArr2;
protected void onPreExecute() {
//progress.show();
}
#Override
protected List<GeoPoint> doInBackground(String... arg0) {
String result = "";
int responseCode = 0;
int executeCount = 0;
HttpResponse response;
StringBuilder sb = new StringBuilder();
String line;
try
{
HttpClient client = new DefaultHttpClient();
HttpGet httppost = new HttpGet("http://xxxx/ccvo/mel-asset-data/query.php?lon="+ arg0[0].toString() + "&lat="+ arg0[1].toString() +"&within=" + arg0[2].toString() + "&keyword="+ arg0[3].toString().replace(" ", "%20"));
do
{
// progressDialog.setMessage("Passing paratmeters.. ("+(executeCount+1)+"/5)");
// Execute HTTP Post Request
executeCount++;
response = client.execute(httppost);
responseCode = response.getStatusLine().getStatusCode();
} while (executeCount < 5 && responseCode == 408);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
while ((line = rd.readLine()) != null)
{
result = line.trim();
sb.append(line);
}
}catch (Exception e2) {
responseCode = 408;
e2.printStackTrace();
}
rst = result.toString();
// splits everything
if(rst != null && rst.length() > 0)
{
strArr1 = rst.split("\\|");
for(int i=0;i<strArr1.length;i++)
{
// Log.d("Results", "Array size1.1 " + i);
Log.v("Results", "Array split1.2 " + strArr1[i] );
if(strArr1[i] != null && strArr1[i].length() >0 && strArr1[i].contains(","))
{
strArr2 = strArr1[i].split(",");
for(int j=0; j<strArr2.length ;j++)
{
double y =0;
double x =0;
if(j == 1)
{
/// x
//Log.d("Results", "2If statem " + strArr2[j] );
x = Double.parseDouble(strArr2[j]);
y = Double.parseDouble(strArr2[j+1]);
geoPointsArray.add(new GeoPoint((int)(x*1e6), (int)(y*1e6)));
Log.d("geoPointsArray", "geoPointsArray " + geoPointsArray.toString() );
}
}
}
}
}
return geoPointsArray;
}
#Override
protected void onProgressUpdate(GeoPoint... progress1) {
theRouteDraw(progress1[0]);
geoPointsArray.add(progress1[0]);
int lon=progress1[0].getLongitudeE6();
int lat=progress1[0].getLatitudeE6();
GeoPoint p2=new GeoPoint(lon,lat);
geoPointsArray.add(p2);
initMyLocation();
}
#Override
protected void onPostExecute(List<GeoPoint> geoPointsArray)
{
//super.onPostExecute(geoPointsArray);
progress.dismiss();
//startActivity(i);
//i.getCharExtra("Geop", geoPointsArray);
Log.d("Lista", " check " + geoPointsArray.size());
// theRouteDraw(geoPointsArray);
}
}
}
My MirItemizedOverlay Class:
class MirItemizedOverlay extends ItemizedOverlay {
private List<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
public MirItemizedOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
// TODO Auto-generated constructor stub
}
#Override
protected OverlayItem createItem(int i) {
return mOverlays.get(i);
}
#Override
public int size() {
return mOverlays.size();
}
public void addOverlayItem(OverlayItem overlayItem) {
mOverlays.add(overlayItem);
populate();
}
#Override
public boolean onTouchEvent(MotionEvent event, MapView mapView)
{
//---when user lifts his finger---
if (event.getAction() == 1) {
GeoPoint p = mapView.getProjection().fromPixels(
(int) event.getX(),
(int) event.getY());
Toast.makeText(getBaseContext(),
p.getLatitudeE6() / 1E6 + "," +
p.getLongitudeE6() /1E6 ,
Toast.LENGTH_SHORT).show();
}
return false;
}
private Context getBaseContext() {
// TODO Auto-generated method stub
return null;
}
public void addOverlayItem(int lat, int lon, String title) {
GeoPoint point = new GeoPoint(lat, lon);
OverlayItem overlayItem = new OverlayItem(point, title, null);
addOverlayItem(overlayItem);
}
/* public void addOverlayItem(GeoPoint point , String title) {
OverlayItem overlayItem = new OverlayItem(point, title, null);
addOverlayItem(overlayItem);
//GeoPoint point = new GeoPoint(lat, lon);
}*/
}
The error :
: E/AndroidRuntime(2752): FATAL EXCEPTION: main
: E/AndroidRuntime(2752): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.phooogle/com.example.phooogle.GoogleMapsAppActivity}: java.lang.NullPointerException
: E/AndroidRuntime(2752): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
: E/AndroidRuntime(2752): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
: E/AndroidRuntime(2752): at android.app.ActivityThread.access$600(ActivityThread.java:130)
: E/AndroidRuntime(2752): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
: E/AndroidRuntime(2752): at android.os.Handler.dispatchMessage(Handler.java:99)
: E/AndroidRuntime(2752): at android.os.Looper.loop(Looper.java:137)
: E/AndroidRuntime(2752): at android.app.ActivityThread.main(ActivityThread.java:4745)
: E/AndroidRuntime(2752): at java.lang.reflect.Method.invokeNative(Native Method)
: E/AndroidRuntime(2752): at java.lang.reflect.Method.invoke(Method.java:511)
: E/AndroidRuntime(2752): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
: E/AndroidRuntime(2752): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
: E/AndroidRuntime(2752): at dalvik.system.NativeStart.main(Native Method)
: E/AndroidRuntime(2752): Caused by: java.lang.NullPointerException
: E/AndroidRuntime(2752): at com.example.phooogle.GoogleMapsAppActivity.onCreate(GoogleMapsAppActivity.java:68)
I've tried several ways to do like I tried to change the addOverlayItem method to accept the GeoPoitns from the AsyncTask return but also failed. I almost gave me on this. :)
Update
The problem resolved. Here is the fix:
try {
//String[] arrs = init_task.strArr2;
List<GeoPoint> geoL = init_task.get();
//Log.d(" Get the size " , " Geo List " + geoL.get(1).toString());
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mc = mapView.getController();
List<Overlay> listOfOverlays = mapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.poke);
MyItemizedOverlay itemizedoverlay = new MyItemizedOverlay(drawable, this);
for ( int i = 0; i < geoL.size() ; i++)
{
OverlayItem overlayitem1 = new OverlayItem(geoL.get(i), Selectedword + "s found! " , "It's withing " + selectedDistance + " To your position");
itemizedoverlay.addOverlay(overlayitem1);
listOfOverlays.add(itemizedoverlay);
}
//mc.animateTo(geoL.get(1));
mc.setCenter(new GeoPoint((int) (1E6 * gps.getLatitude() ), (int) (1E6 * gps.getLongitude() ))); // Some where .
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} finally {}
initMap();
initMyLocation();
// theRouteDraw();
Your issue is that mapView is null, you haven't called initMap() yet. This causes mapView.getOverlays().add(itemizedOverlay ); to fail.
In my mapview, Used geocding inside SingleTapUp.
Whenever zoom controls of mapview are used, singleTapUp also gets invoked.
Any suggestions to overcome this scenario.
The code in my main method
public static TextView info;
private MapController mapController;
private MapView mapView;
public LocationManager orgManager;
private MyOverlays itemizedoverlay, blackmarker;
public boolean gps_enabled = false;
public boolean network_enabled = false;
public Criteria c;
public String bestProvider;
public double orginLongitude, orginLatitude, destLongtitude, destLatitude,
currLatitude, currLongtitude, lat, lon;
public boolean isLongPress= false, GPSfix = false;
Location originLocation = new Location("source");
Location currLocation = new Location("current");
Location destinationLocation = new Location("destination");
Location fixlocation= new Location("fix");
NotificationManager nm;
Vibrator v;
MediaPlayer mp = new MediaPlayer();
private TextToSpeech myTTS;
private int MY_DATA_CHECK_CODE = 0;
private List<Overlay> mapOverlays;
private Projection projection;
GestureDetector gestureScanner;
long lastGesture = System.currentTimeMillis();
GeoPoint markerPoint = null;
private int count = 0;
MyLocationOverlay mo;
public GeoPoint source;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_layout);
info = (TextView) findViewById(R.id.infopane);
mapView = (MapView) findViewById(R.id.mapView);
//Button myloc = (Button)findViewById(R.id.myloc);
info.setText("Please Tap on the Map");
orgManager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
mapView.setBuiltInZoomControls(true);
mapView.setSatellite(true);
markerPoint = null;
mapController = mapView.getController();
mapController.setZoom(16); // Zoom 1 is world view
mapView.invalidate();
mo = new MyLocationOverlay(MapClass.this, mapView);
mapView.getOverlays().add(mo);
mapOverlays = mapView.getOverlays();
projection = mapView.getProjection();
Drawable drawable = this.getResources()
.getDrawable(R.drawable.mark_red);
Drawable black_marker = this.getResources().getDrawable(
R.drawable.marker_black);
itemizedoverlay = new MyOverlays(drawable);
blackmarker = new MyOverlays(black_marker);
try {
gps_enabled = orgManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
Log.i("success", "Gps:" + String.valueOf(gps_enabled)+ "N/w:" + String.valueOf(network_enabled) );
} catch (Exception ex) {
Log.i("sample", "sample");
}
if (!gps_enabled) {
Log.i("failure", "Gps:" + String.valueOf(gps_enabled)+ "N/W:" + String.valueOf(network_enabled) );
final AlertDialog.Builder builder = new AlertDialog.Builder(MapClass.this);
builder.setTitle("Attention!");
builder.setMessage("Sorry, location is not determined. Please open app after enabling GPS & wireless networks").setCancelable(false).setPositiveButton("OK", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
startActivity(new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
}
if(gps_enabled){
orgManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
fixlocation = orgManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Log.i("fix", String.valueOf(fixlocation.getLatitude() + fixlocation.getLongitude()));
if (fixlocation!=null){
originLocation.setLatitude(fixlocation.getLatitude());
originLocation.setLongitude(fixlocation.getLongitude());
Log.i("origin fix", String.valueOf(originLocation.getLatitude() + originLocation.getLongitude()));
GPSfix = true;
}else Toast.makeText(MapClass.this, "", Toast.LENGTH_SHORT).show();
}
if (GPSfix) {
// double a = originLocation.getLatitude();
// double b = originLocation.getLongitude();
source = new GeoPoint(
(int) ((fixlocation.getLatitude()) * 1E6),
(int) ((fixlocation.getLongitude()) * 1E6));
mapController.animateTo(source);
mapView.getMapCenter();
createMarker();
Toast.makeText( MapClass.this," Source GPS Values Latitude: "
+ fixlocation.getLatitude() + " Longitude: "
+ fixlocation.getLongitude(), Toast.LENGTH_SHORT).show();
}
else Toast.makeText(MapClass.this, "Wait for GPS", Toast.LENGTH_SHORT).show();
gestureScanner = new GestureDetector(this, this);
}
The code in gesture scanner method.
onLongPress
#Override
public void onLongPress(final MotionEvent e) {
// TODO Auto-generated method stuMapClass Toast.makeText(MapClass.this,
// "LongPress", Toast.LENGTH_SHORT)
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MapClass.this);
// Setting Dialog Title
alertDialog.setTitle("Alert!!");
// Setting Dialog Message
alertDialog.setMessage("Do you want to select this as destination");
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("YES",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog
String add = "";
GeoPoint geopoint = mapView.getProjection().fromPixels(
(int) e.getX(), (int) e.getY());
// latitude
lat = geopoint.getLatitudeE6() / 1E6;
// longitude
lon = geopoint.getLongitudeE6() / 1E6;
Geocoder geoCoder = new Geocoder(getBaseContext(),
Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(
geopoint.getLatitudeE6() / 1E6,
geopoint.getLongitudeE6() / 1E6, 1);
if (addresses.size() > 0) {
for (int i = 0; i < addresses.get(0)
.getMaxAddressLineIndex(); i++)
add += addresses.get(0).getAddressLine(i)
+ "\n";
}
Toast.makeText(getBaseContext(), add,
Toast.LENGTH_SHORT).show();
} catch (IOException ioe) {
ioe.printStackTrace();
}
mapOverlays.add(new MyOverlay((originLocation
.getLatitude()),
(originLocation.getLongitude()), lat, lon));
destinationLocation.setLatitude(lat);
destinationLocation.setLongitude(lon);
String distance = Float.toString((originLocation
.distanceTo(destinationLocation) / 1000));
createblack();
count++;
Toast.makeText(getBaseContext(), distance + "kms",
Toast.LENGTH_SHORT).show();
info.setText("Selected destination is " + "\n" + add
+ "\n" + " The journey distance is " + distance
+ " Kms ");
mapView.postInvalidate();
isLongPress = true;
mapController.animateTo(source);
mapView.getMapCenter();
}
private void createblack() {
// TODO Auto-generated method stub
GeoPoint p = new GeoPoint((int) (lat * 1E6),
(int) (lon * 1E6));
OverlayItem overlayitem = new OverlayItem(p,
"Destination", "");
blackmarker.addOverlay(overlayitem);
mapView.getOverlays().add(blackmarker);
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton("NO",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog
Toast.makeText(getApplicationContext(),
"You clicked on NO", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
OnsingeTapup
#Override
public boolean onSingleTapUp(MotionEvent arg0) {
// TODO Auto-generated method stub
Log.i("SingleTap", arg0.toString());
GeoPoint geopoint = mapView.getProjection().fromPixels(
(int) arg0.getX(), (int) arg0.getY());
Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(
geopoint.getLatitudeE6() / 1E6,
geopoint.getLongitudeE6() / 1E6, 1);
String add = "";
if (addresses.size() > 0) {
for (int i = 0; i < addresses.get(0).getMaxAddressLineIndex(); i++)
add += addresses.get(0).getAddressLine(i) + "\n";
}
if (count == 0) {
info.setText("The location you have selected is" + "\n" + add
+ "\n" + "To confirm it longpress the location");
} else
Toast.makeText(getBaseContext(), add, Toast.LENGTH_SHORT)
.show();
} catch (IOException ioe2) {
ioe2.printStackTrace();
}
return true;
}
Additionally used a Overlay Class to place markers..
It is a bit hard to debug your code as there are important parts missing but I would suggest taking a look at the following answer to a similar StackOverflow question:
https://stackoverflow.com/a/2990749/376016
The proposed solution for recognising gestures on the MapView is to create a custom Overlay that only handles touch events and insert it as the first overlay. Using this approach I was able to create a small test application that used most of your code and correctly ignored the pinch to zoom gestures on the MapView.
I have displayed the map in my app by using the following code. I have retrieved info from the database and displayed the map. Now i want to add marker to the retrieved location...
googleMao.java
public class googleMap extends MapActivity{
private MapView mapView;
private MapController mc;
GeoPoint p;
long s;
Cursor cur;
SQLiteDatabase db;
createSqliteHelper csh;
String query;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
// String query = getIntent().getStringExtra("value");
// here is calling the map string query
s = getIntent().getLongExtra("value",2);
map();
mapView = (MapView) findViewById(R.id.mapview1);
LinearLayout zoomLayout = (LinearLayout)findViewById(R.id.zoom);
View zoomView = mapView.getZoomControls();
zoomLayout.addView(zoomView,
new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
//mapView.displayZoomControls(true);
mapView.setBuiltInZoomControls(true);
mc = mapView.getController();
String coordinates[] = {"1.352566007", "103.78921587"};
double lat = Double.parseDouble(coordinates[0]);
double lng = Double.parseDouble(coordinates[1]);
Geocoder geoCoder = new Geocoder(this, Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocationName(query, 5);
String add = "";
if (addresses.size() > 0) {
p = new GeoPoint(
(int) (addresses.get(0).getLatitude() * 1E6),
(int) (addresses.get(0).getLongitude() * 1E6));
mc.animateTo(p);
mapView.invalidate();
mc.setZoom(6);
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected boolean isRouteDisplayed() {
// Required by MapActivity
return false;
}
public void map()
{
String[] str={"type"};
int[] i={R.id.type};
csh=new createSqliteHelper(this);
db=csh.getReadableDatabase();
cur=db.rawQuery("select type from restaurants where _id="+s,null);
if(cur.moveToFirst())
{
query = cur.getString(cur.getColumnIndex("type"));
}
}
}
You need to create an ItemizedOverlay for that. Here is one sample project from my books that shows adding an ItemizedOverlay to a MapView.