How to get Latitude/Longitude from JSON responsed by google map apis - android

I am not able to properly extract out the latitude and longitude point set to draw route further. Can anybody get me the code to do so?
Thanks in advance

public class MapprojectActivity extends MapActivity {
/** Called when the activity is first created. */
static final String TAG_RESULTS = "results";
static final String TAG_GEO = "geometry";
static final String TAG_LOCATION = "location";
static final String TAG_LAT = "lat";
static final String TAG_LNG = "lng";
JSONArray res = null;
MapView mapView;
List<Overlay> mapOverlays;
Drawable drawable;
MyItemizedOverlay itemizedOverlay;
static String url = "http://maps.google.com/maps/api/geocode/json?address=guindy,+chennai,+IN&sensor=false";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
TextView lattv=(TextView)findViewById(R.id.lat);
TextView lngtv=(TextView)findViewById(R.id.lng);
JSONParstring jParser = new JSONParstring();
// getting JSON string from URL
try
{
JSONObject jobj = new JSONObject(json);
res = jobj.getJSONArray(TAG_RESULTS);
for(int i = 0; i < res.length(); i++){
JSONObject c = res.getJSONObject(i);
JSONObject loc = c.optJSONObject(TAG_GEO).optJSONObject(TAG_LOCATION);
String lat =loc.getString(TAG_LAT);
String lng = loc.getString(TAG_LNG);
lattv.setText(lat);
lngtv.setText(lng);
}
}
catch (JSONException e){ }
String i=(String) lattv.getText();
String j=(String) lngtv.getText();
double lat1 = Double.parseDouble(i);
double lng1 = Double.parseDouble(j);
mapView = (MapView) findViewById(R.id.map_view);
mapView.setBuiltInZoomControls(false);
mapOverlays = mapView.getOverlays();
drawable = getResources().getDrawable(R.drawable.mark1);
itemizedOverlay = new MyItemizedOverlay(drawable, mapView);
GeoPoint point = new GeoPoint((int)(lat1*1E6),(int)(lng1*1E6));
OverlayItem overlayItem = new OverlayItem(point, "Amy Jones",
"(checked in Lemon-tree with friends lisa wong, paul jones)");
itemizedOverlay.addOverlay(overlayItem);
mapOverlays.add(itemizedOverlay);
final MapController mc = mapView.getController();
mc.animateTo(point);
mc.setZoom(16);
// Integer i = Integer.valueOf((String) lattv.getText());
// Integer j = Integer.valueOf((String) lngtv.getText());
// // first overlay
}
protected boolean isRouteDisplayed() {
return false;
}
}

Here is to get Latitude/Longitude from JSON http://blog.synyx.de/2010/06/routing-driving-directions-on-android-part-1-get-the-route/
And this is how to draw a route http://blog.synyx.de/2010/06/routing-driving-directions-on-android-%E2%80%93-part-2-draw-the-route/
u should study it. i hope it'll help.

Related

Google Maps And ListView in one activity in android?

I am trying to fit a Google Maps View and a ListView into one activity. The MapsView shall take 2/3 of the upper side, and the list 1/3 of the lower side (in portrait).
in this way assume it as portrait:
Both, the MapsView and the ListView, will receive the same JSON information, they will get onCreate(). I was already able to fit the MapsView on 2/3 of the screen, but the ListView wont receive any data. Can someone tell me, how to adress a ListView correct, when the superclass isnt ListActivity?
here is my code:
// url to make request
private static String url = ""; //here pass the url
// JSON Node names
private static final String TAG_LOCATION = "location";
private static final String TAG_LOCATION1= "location";
private static final String TAG_LOCATION_ID = "LocationID";
private static final String TAG_NAME = "Name";
private static final String TAG_PHONE = "Phone";
private static final String TAG_FORMATTED_PHONE = "FormattedPhone";
private static final String TAG_ADDRESS = "Address";
private static final String TAG_CROSS_STREET = "CrossStreet";
private static final String TAG_LAT = "Lat";
private static final String TAG_LNG = "Lng";
private static final String TAG_DISTANCE= "Distance";
private static final String TAG_POSTAL_CODE = "PostalCode";
private static final String TAG_CITY = "City";
private static final String TAG_STATE = "State";
private static final String TAG_COUNTRY= "Country";
// contacts JSONArray
JSONArray location = null;
JSONObject location1=null;
ListView locationList;
private MapView mapView;
LocationManager lm;
LocationListener locationListener;
MapController mapController;
private ListAdapter adapter;
private static final double lat = 11.9333;
private static final double lng = 108.417;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_map);
locationList=( ListView)findViewById(R.id.list_Surroundings);
locationList.setAdapter(adapter);
// Hashmap for ListView
ArrayList<HashMap<String, String>> locationList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Category
location=json.getJSONArray(TAG_LOCATION);
//looping through all categories
for(int i = 0; i < location.length(); i++){
JSONObject c = location.getJSONObject(i);
JSONObject c1=c.getJSONObject(TAG_LOCATION1);
// Storing each json item in variable
String LocationID = c1.getString(TAG_LOCATION_ID);
String Name = c1.getString(TAG_NAME);
String Phone = c1.getString(TAG_PHONE);
String FormattedPhone = c1.getString(TAG_FORMATTED_PHONE);
String Address = c1.getString(TAG_ADDRESS);
String CrossStreet = c1.getString(TAG_CROSS_STREET);
String Lat = c1.getString(TAG_LAT);
String Lng = c1.getString(TAG_LNG);
String Distance = c1.getString(TAG_DISTANCE);
String PostalCode = c1.getString(TAG_POSTAL_CODE);
String City = c1.getString(TAG_CITY);
String State = c1.getString(TAG_STATE);
String Country = c1.getString(TAG_COUNTRY);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_LOCATION_ID, LocationID);
map.put(TAG_NAME, Name);
map.put(TAG_PHONE, Phone);
map.put(TAG_FORMATTED_PHONE, FormattedPhone);
map.put(TAG_ADDRESS, Address);
map.put(TAG_CROSS_STREET, CrossStreet);
map.put(TAG_LAT, Lat);
map.put(TAG_LNG, Lng);
map.put(TAG_DISTANCE, Distance);
map.put(TAG_POSTAL_CODE, PostalCode);
map.put(TAG_CITY, City);
map.put(TAG_STATE, State);
map.put(TAG_COUNTRY, Country);
// adding HashList to ArrayList
locationList.add(map);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
adapter = new SimpleAdapter(this, locationList,
R.layout.list_item,
new String[] { TAG_NAME }, new int[] {
R.id.name});
mapView = (MapView) findViewById(R.id.mapView);
mapView.setBuiltInZoomControls(true);
List mapOverlays = mapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(
R.drawable.map_pin_red);
CustomItemizedOverlay itemizedOverlay = new CustomItemizedOverlay(
drawable, this);
GeoPoint point = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
OverlayItem overlayitem = new OverlayItem(point, "Hello",
"I'm in Athens, Greece!");
itemizedOverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedOverlay);
mapController = mapView.getController();
mapController.animateTo(point);
mapController.setZoom(10);
lm=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationListener= new MylocationListener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
public class MylocationListener implements LocationListener{
#Override
public void onLocationChanged(Location loc) {
// TODO Auto-generated method stub
if(loc!=null){
Toast.makeText(getBaseContext(), "Location Changed : Lat:" +loc.getLatitude() + "Lng: " + loc.getLongitude(), Toast.LENGTH_SHORT).show();
}
GeoPoint point = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
mapController.animateTo(point);
mapController.setZoom(10);
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
You have to create the adapter BEFORE setting it as the adapter of the ListView. Also, you have two variables named LocationList, which is generally bad practice. Try:
public void onCreate(Bundle savedInstanceState) {
// Hashmap for ListView
ArrayList<HashMap<String, String>> listOfLocations = new ArrayList<HashMap<String, String>>();
... // existing code here
adapter = new SimpleAdapter(this, listOfLocations,
R.layout.list_item,
new String[] { TAG_NAME }, new int[] {
R.id.name});
locationList.setAdapter(adapter);
}

parsing Json on android

this is my code
{ public class MainActivity extends MapActivity {
private MapView mapView;
//test start
private static String url = "http://localhost/test/json_parser.php";
private static final String TAG_PLACE="place";
private static final String TAG_ID="id";
private static final String TAG_NAME_PLACE="name_place";
private static final String TAG_LATITUDE="latitude";
private static final String TAG_LONGITUDE="longitude";
private static final String TAG_PERSON="person";
private static final String TAG_DATE="date";
private static final String TAG_TIME="time";
JSONArray place = null;
String[] p_lat=null;
String[] p_lon=null;
String id;
String name_place;
String latitude;
String longitude;
String person;
String date;
String time;
//test end
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mapView=(MapView)findViewById(R.id.mapview);
Drawable marker=getResources().getDrawable(R.drawable.marker);
marker.setBounds((int)(-marker.getIntrinsicWidth()/2),-marker.getIntrinsicHeight(), (int)(marker.getIntrinsicWidth()/2),0);
InterestingLocations funPlaces=new InterestingLocations(marker);
mapView.getOverlays().add(funPlaces);
GeoPoint pt=funPlaces.getCenterPt();
int latSpan=funPlaces.getLatSpanE6();
int lonSpan=funPlaces.getLonSpanE6();
Log.v("Overlays","Lat span is" + latSpan);
Log.v("Overlays","Lon span is" + lonSpan);
MapController mc=mapView.getController();
mc.setCenter(pt);
mc.zoomToSpan((int)(latSpan*1.5),(int)(lonSpan*1.5));
//test start
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url);
//System.out.println("Testingggg..." + json.length());
//test end
//test start
/*
try{
place = json.getJSONArray(TAG_PLACE);
for(int i=0;i<place.length();i++){
JSONObject c = place.getJSONObject(i);
id = c.getString(TAG_ID);
name_place = c.getString(TAG_NAME_PLACE);
latitude = c.getString(TAG_LATITUDE);
//p_lat[i]=latitude;
longitude = c.getString(TAG_LONGITUDE);
//p_lon[i]=longitude;
person = c.getString(TAG_PERSON);
date = c.getString(TAG_DATE);
time = c.getString(TAG_TIME);
}
}catch(JSONException e){
e.printStackTrace();
}/*
System.out.print(p_lat[0]);
System.out.print(p_lon[0]);
*/
//test end
}
public void myClickHandler(View target){
switch(target.getId()){
case R.id.zoomin:
mapView.getController().zoomIn();
break;
case R.id.zoomout:
mapView.getController().zoomOut();
break;
case R.id.sat:
mapView.setSatellite(true);
break;
case R.id.street:
mapView.setStreetView(true);
break;
case R.id.traffic:
mapView.setTraffic(true);
break;
case R.id.normal:
mapView.setSatellite(false);
mapView.setStreetView(false);
mapView.setTraffic(false);
break;
}
mapView.postInvalidateDelayed(2000);
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
}
i am getting problem when i delete comment from
//System.out.println("Testingggg..." + json.length());
and when i delete comment from
/*
try{
place = json.getJSONArray(TAG_PLACE);
for(int i=0;i<place.length();i++){
JSONObject c = place.getJSONObject(i); .....
i tried many things i haven't succeed
the problem is in parsing json
and thanks for every one
this is my json file
{"place": [{"id":"1","name_place":"Jedeida","latitude":"36.502234","longitude":"9.561264","person":"ahmed","date":"2012-08-01","time":"07:45:50"},
{"id":"2","name_place":"jedeida","latitude":"36.502234","longitude":"9.561109","person":"ahmed","date":"2012-08-01","time":"07:46:30"},{"id":"3","name_place":"jedeida","latitude":"36.501676","longitude":"9.562135","person":"ahmed","date":"2012-08-01","time":"07:48:03"},{"id":"4","name_place":"jedeida","latitude":"36.50083","longitude":"9.563069","person":"ahmed","date":"2012-08-01","time":"07:50:05"},{"id":"5","name_place":"Tebourba","latitude":"36.51029","longitude":"9.553043","person":"ali","date":"2012-08-02","time":"06:05:41"},{"id":"6","name_place":"jedeida","latitude":"36.504886","longitude":"9.553918","person":"ali","date":"2012-08-02","time":"06:07:04"},{"id":"7","name_place":"jedeida","latitude":"36.503503","longitude":"9.555477","person":"ali","date":"2012-08-02","time":"06:09:23"},{"id":"8","name_place":"jedeida","latitude":"36.50211","longitude":"9.561287","person":"ali","date":"2012-08-02","time":"06:11:40"},{"id":"9","name_place":"jedeida","latitude":"36.501208","longitude":"9.562281","person":"ali","date":"2012-08-02","time":"06:13:26"},{"id":"10","name_place":"jedeida","latitude":"36.500477","longitude":"9.563136","person":"ali","date":"2012-08-02","time":"06:15:01"}]}
and this is a link to logcat file
enter link description here
You declare your string array p_lat & p_lon as null that's why your application get Force Closed. Your JSON parsing code is perfectly working.
You have to initialize string array with specific size as below.
String[] p_lat= new String[10];
String[] p_lon= new String[10];
You can also your ArrayList for better performance.
JSONObject c = place.getJSONObject(i);
are you sure that every index (i) is a jsonobject and not a other value/string ?
System.out.println("Testingggg..." + json.length());
try Integer.toString(json.length())
i am using wampserver and it appear that i must change
private static String url = "http://localhost/test/json_parser.php";
to
private static String url = "http://10.0.2.2/test/json_parser.php";
the problem seems to be caused by the incorrect address
this is why when you have problem don't forget to use log.d("","");

How to put JSON lattitude and longitude on the map [duplicate]

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);
}

Map latitude and longitude is showing in sea in android?

From a json feed am getting all the latitude and longitude and adding all in mapview. Am gettin different markers.but all the points are showing in sea. this is my code. can anyone help me please
MapItemizedOverlay itemizedoverlay;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
url = "http://dentonsweb.com/app/html/android/get.php?what=Hotels&lat=51.507222&lon=-0.1275&pg=0";
System.out.println("url is "+url);
Jsonfunctions jParser = new Jsonfunctions();
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
results = json.getJSONArray(TAG_RESULTS);
// looping through All Contacts
for (int i = 0; i < results.length(); i++) {
JSONObject c = results.getJSONObject(i);
id = c.getString(TAG_ID);
name = c.getString(TAG_NAME);
System.out.println("name is " + name);
adress = c.getString(TAG_ADRRESS);
latitude = c.getString(TAG_LATITUDE);
latitudeAry.add(c.getString(TAG_LATITUDE).toString());
longitude = c.getString(TAG_lONGITUDE);
latitudeAry.add(c.getString(TAG_lONGITUDE).toString());
distance = c.getString(TAG_DISTANCE);
image = c.getString(TAG_IMAGE);
phone = c.getString(TAG_TELEPHONE);
telphonenumberAry
.add(c.getString(TAG_TELEPHONE).toString());
NameAry.add(c.getString(TAG_NAME).toString());
resourceAry.add(new ResourceClass(point,id, name, adress,image,
distance, latitude, longitude, phone));
System.out.println("arraooosdospodpsodps " + resourceAry);
}
} catch (JSONException e) {
e.printStackTrace();
}
mapView = (MapView) findViewById(R.id.mapView);
mapView.setBuiltInZoomControls(true);
mapView.setSatellite(false);
mc = mapView.getController();
listOfOverlays = mapView.getOverlays();
drawable = this.getResources().getDrawable(
R.drawable.pin);
itemizedoverlay = new MapItemizedOverlay(drawable,mapView);
for (int i = 0; i < resourceAry.size(); i++) {
// latitude = resourceAry.get(i).getLatitude();
System.out.println("latitude is " + latitude);
String latitude = resourceAry.get(i).getLatitude();
String longitude = resourceAry.get(i).getLongitude();
// longitude = resourceAry.get(i).getLongitude();
String name = resourceAry.get(i).getName();
System.out.println("Name is" + name);
String adress = resourceAry.get(i).getAdress();
if (!latitude.equals("") && !longitude.equals("")) {
Double latitude_next = Double.parseDouble(latitude);
Double longitude_next = Double.parseDouble(longitude);
point = new GeoPoint((int) (latitude_next * 1E6),
(int) (longitude_next * 1E6));
System.out.println("point is " + point);
overlayitem = new OverlayItem(point,resourceAry.get(i).getName(),resourceAry.get(i).getAdress());
// System.out.println( " spanned text: " +
// Html.fromHtml(Texte));
itemizedoverlay.addOverlay(overlayitem);
listOfOverlays.add(itemizedoverlay);
}
}
mc.animateTo(point);
mc.setZoom(13);
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
#harish --
You get latitude & longitudes like 51.509998321533,-0.12999999523163
but in android geopoint accepts only int values.
now create a function which will take these values & restric them upto 6 decimal points & you will get result as you wanted
Function will be like
double roundTwoDecimals(double d){
DecimalFormat twoDForm = new DecimalFormat("#.######");
return Double.valueOf(twoDForm.format(d));
}
this way you will get double value & then multiply it with 10E6 & you will get int which you need to use in creating GeoPoints..
I am not suere if it makes a difference but the line
latitudeAry.add(c.getString(TAG_lONGITUDE).toString());
has a lowercase L in lONGITUDE

Adding marker to the retrieved location

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.

Categories

Resources