I'm populating a Google map with markers, I don't get errors and my variables are getting their values but it isnt populating any markers. It just show one marker and it is my current location.
here is the code that i call when populating:
private void showData() {
int count = users.length();
for(;i<=count;i++) {
try {
JSONObject jsonObject = users.getJSONObject(i);
maplat = Double.parseDouble(jsonObject.getString(lat));
maplng = Double.parseDouble(jsonObject.getString(lng));
MarkerOptions marker = new MarkerOptions().position(new LatLng(maplat, maplng)).title("Hello Maps");
marker.icon(BitmapDescriptorFactory.fromResource(R.drawable.pin));
googleMap.addMarker(marker);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
My whole code:
public class MapActivity extends AppCompatActivity{
private GoogleMap googleMap;
double curLat;
double curLng;
double maplat;
double maplng;
private static final String JSON_ARRAY = "result";
private static final String lat= "lat";
private static final String lng = "lng";
private JSONArray users = null;
private String q;
private static final String GET_URL = "http://testevent.site88.net/getlocation.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
GPSTracker gps = new GPSTracker(this);
curLat = gps.getLatitude();
curLng = gps.getLongitude();
try {
// Loading map
initilizeMap();
} catch (Exception e) {
e.printStackTrace();
}
}
private void extractJSON(){
try {
JSONObject jsonObject = new JSONObject(q);
users = jsonObject.getJSONArray(JSON_ARRAY);
} catch (JSONException e) {
e.printStackTrace();
}
}
private void showData() {
int count = users.length();
for(int i = 0;i<=count;i++) {
try {
JSONObject jsonObject = users.getJSONObject(i);
maplat = Double.parseDouble(jsonObject.getString(lat));
maplng = Double.parseDouble(jsonObject.getString(lng));
MarkerOptions marker = new MarkerOptions().position(new LatLng(maplat, maplng)).title("Hello Maps");
marker.icon(BitmapDescriptorFactory.fromResource(R.drawable.pin));
googleMap.addMarker(marker);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private void getJSON(String url) {
class GetJSON extends AsyncTask<String, Void, String>{
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MapActivity.this, "Please Wait...",null,true,true);
}
#Override
protected String doInBackground(String... params) {
String uri = params[0];
BufferedReader bufferedReader = null;
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while((json = bufferedReader.readLine())!= null){
sb.append(json+"\n");
}
return sb.toString().trim();
}catch(Exception e){
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
q=s;
extractJSON();
showData();
MarkerOptions marker = new MarkerOptions().position(new LatLng(curLat, curLng)).title("Hello Maps");
// Changing marker icon
marker.icon(BitmapDescriptorFactory.fromResource(R.drawable.pin));
// adding marker
googleMap.addMarker(marker);
}
}
GetJSON gj = new GetJSON();
gj.execute(url);
}
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(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
getJSON(GET_URL);
}
#Override
protected void onResume() {
super.onResume();
initilizeMap();
}
}
Related
I need to show a bus location on the map, I have latitude and longitude saved in my database. To retrieve the Latitude and Longitude i am using AsynTask. But i think there is some problem with my code, app crashes if call AsyncTask in onMapReady. I checked without calling AsyncTask giving manual latitude and longitude, it works fine. Please help me fix the issue.
This is my code:
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
GetLocation getLocation = new GetLocation(getApplicationContext());
getLocation.execute();
}
public class GetLocation extends AsyncTask<String,Void,String> {
Context context;
GetLocation(Context ctx){
context = ctx;
}
#Override
protected String doInBackground(String... params) {
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
String login_url = "https://www.mywebsite.com/android/getlonglatt.php";
try {
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
String result="";
while ((line = bufferedReader.readLine())!=null){
result += line;
}
JSONObject jsonObject = new JSONObject(result);
String latitudedb = (String) jsonObject.get("latitude");
String longitudedb = (String) jsonObject.get("longitude");
String busnum = (String) jsonObject.get("busnum");
Double newlatt = Double.valueOf(latitudedb);
Double newlong = Double.valueOf(longitudedb);
LatLng location = new LatLng(newlatt, newlong);
MarkerOptions options = new MarkerOptions().position(location).title(busnum);
mMap.addMarker(options);
mMap.moveCamera(CameraUpdateFactory.newLatLng(location));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(location,19.2f));
bufferedReader.close();
httpURLConnection.disconnect();
} catch (JSONException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
protected void onProgressUpdate(Void... values) {
}
}
I want to load markers from json file assets folder offline and show it on the map.
Previously I could shown the markers as textview but I can't show them on map.
The app shows the map but doesn't show the markers.
I don't know why.
stations.json
[
{
"name": "JAVANMARDAN1",
"lat": 35.747394,
"lang": 51.267577
}
]
map.xml
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.google.android.gms.maps.SupportMapFragment"/>
MapsActivity
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private Marker marker;
private GoogleMap mMap;
public MapsActivity() throws JSONException {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
new AsyncTaskGetMareker().execute();
}
public String getJSONFromAssets() {
String json = null;
try {
InputStream inputData = getAssets().open("stations.json");
int size = inputData.available();
byte[] buffer = new byte[size];
inputData.read(buffer);
inputData.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
private class AsyncTaskGetMareker extends AsyncTask
<String , String, JSONArray>{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected JSONArray doInBackground(String... strings) {
return null;
}
protected void onPostExecute (JSONArray result){
if (result !=null){
for (int i =0; i <result.length(); i++){
JSONObject jsonObject= null;
try {
jsonObject= result.getJSONObject(i);
String name=jsonObject.getString("name");
String lat=jsonObject.getString("lat");
String lang=jsonObject.getString("lang");
drawMarker(new LatLng(Double.parseDouble(lat),
Double.parseDouble(lang)));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
private void drawMarker(LatLng point) {
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(point);
GoogleMap googleMap = null;
googleMap.addMarker(markerOptions);
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
}
There are multiple problems in your code:
You're not calling getJSONFromAssets() from your AsyncTask
You're executing the AsyncTask before the map has loaded
In your drawMarker() method, you're creating a new GoogleMap reference and setting it to null. This won't work.
Your code was ignoring the name field, which I assume you want as the snippet for the InfoWindow.
Here is updated code, reworked with all of the problems above fixed:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private Marker marker;
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
new AsyncTaskGetMareker().execute();
}
public String getJSONFromAssets() {
String json = null;
try {
InputStream inputData = getAssets().open("stations.json");
int size = inputData.available();
byte[] buffer = new byte[size];
inputData.read(buffer);
inputData.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
private class AsyncTaskGetMareker extends AsyncTask<String , String, JSONArray> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected JSONArray doInBackground(String... strings) {
String stationsJsonString = getJSONFromAssets();
try {
JSONArray stationsJsonArray = new JSONArray(stationsJsonString);
return stationsJsonArray;
} catch (JSONException e) {
e.printStackTrace();
}
//This will only happen if an exception is thrown above:
return null;
}
protected void onPostExecute (JSONArray result){
if (result !=null){
for (int i =0; i <result.length(); i++){
JSONObject jsonObject= null;
try {
jsonObject= result.getJSONObject(i);
String name=jsonObject.getString("name");
String lat=jsonObject.getString("lat");
String lang=jsonObject.getString("lang");
drawMarker(new LatLng(Double.parseDouble(lat),
Double.parseDouble(lang)), name);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
private void drawMarker(LatLng point, String name) {
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(point);
markerOptions.snippet(name);
mMap.addMarker(markerOptions);
}
}
}
I am using AsyncTask to run information to and from my online mySQL database. I am then using JSON parsing to add the information from the database as a marker on my MapBox map. Currently when a user uploads a new marker (washroom in the code) it uploads the information to the database, then runs the onPostExecute method and goes back to the MapsActivity.java. MapsActivity.java should reload the map and display the newly added marker but it doesn't; it only displays the markers that where added before adding the new one. If you close and open the app the markers are updated, displaying all the markers including the new one! Any help would be appreciated!
Part of MapsActivity.java
public class MapsActivity extends FragmentActivity {
private MapView mapView;
private MapboxMap map;
private ImageButton locationToggle;
private LocationServices locationServices;
private String json_string;
private JSONObject jsonObject;
private JSONArray jsonArray;
public static String WASHROOMINFO;
public static String CURRENT_LOCATION;
private static final int PERMISSIONS_LOCATION = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MapboxAccountManager.start(this, getString(R.string.accessToken));
setContentView(R.layout.activity_maps);
//getting location services
locationServices = com.mapbox.mapboxsdk.location.LocationServices.getLocationServices(MapsActivity.this);
//onClick to go to add washroom activity
findViewById(R.id.addWashroom).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (CURRENT_LOCATION != null) {
Intent intent = new Intent(getBaseContext(), AddWashroom.class);
startActivity(intent);
} else {
Toast.makeText(getBaseContext(),"You Must Turn on User Location Before Adding a Washroom!",Toast.LENGTH_LONG).show();
}
}
});
//washrooms have not been loaded in yet
if (!BackgroundTask.WASHROOMS_LOADED) {
//getting database info
String method = "getWashroom";
BackgroundTask backgroundTask = new BackgroundTask(getBaseContext());
backgroundTask.execute(method);
finish();
}
mapView = (MapView) findViewById(R.id.mapview);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(MapboxMap mapboxMap) {
//when map is ready assign mapboxMap variable
map = mapboxMap;
//Washroom loading has been requested and JSON data is ready
if (BackgroundTask.WASHROOMS_LOADED) {
//Getting JSON data from intent
json_string = getIntent().getExtras().getString("json_data");
try {
//new JSON object from JSON data
jsonObject = new JSONObject(json_string);
//gets JSON array from JSON object
jsonArray = jsonObject.getJSONArray("server_response");
//Marker list for buffering markers
List<Marker> markers = new ArrayList<Marker>();
//do this for all markers!
for (int i = 0; i < jsonArray.length(); i++) {
//Single JSON object of single marker
JSONObject JO = jsonArray.getJSONObject(i);
//Dividing location field into lat & lng
String latlng = JO.getString("location");
String[] latlngSplit = latlng.split(" , ",2);
double lat = Double.valueOf(latlngSplit[0]);
double lng = Double.valueOf(latlngSplit[1]);
//adding marker
Marker marker = map.addMarker(new MarkerOptions()
.title(JO.getString("name"))
.setSnippet(JO.getString("price"))
.position(new LatLng(lat,lng))
);
//add marker to markers list.
markers.add(marker);
}
BackgroundTask.WASHROOMS_LOADED = false;
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
locationToggle = (ImageButton) findViewById(R.id.location_toggle);
locationToggle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (map != null) {
//toggle GPS when clicking show location button
toggleGps(!map.isMyLocationEnabled());
}
}
});
}
BackgroundTask (AsyncTask)
class BackgroundTask extends AsyncTask<String, Void, String> {
Context ctx;
public static boolean WASHROOMS_LOADED;
private String JSON_STRING;
private String json_string;
BackgroundTask(Context ctx) {
this.ctx = ctx.getApplicationContext();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
String add_url = "http://appart-software.com/add_washroom.php";
String get_url = "http://appart-software.com/get_washroom.php";
#Override
protected String doInBackground(String... params) {
String method = params[0];
if (method.equals("addWashroom")) {
String location = params[1];
String name = params[2];
String price = params[3];
try {
URL url = new URL(add_url);
HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
httpUrlConnection.setRequestMethod("POST");
httpUrlConnection.setDoOutput(true);
OutputStream outputStream = httpUrlConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
String data_string = URLEncoder.encode("WClocation","UTF-8")+"="+URLEncoder.encode(location,"UTF-8")+"&"+
URLEncoder.encode("WCname","UTF-8")+"="+URLEncoder.encode(name,"UTF-8")+"&"+
URLEncoder.encode("WCprice","UTF-8")+"="+URLEncoder.encode(price,"UTF-8");
bufferedWriter.write(data_string);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpUrlConnection.getInputStream();
inputStream.close();
httpUrlConnection.disconnect();
return "Washroom Added!";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//You want to get washroom info
} else if (method.equals("getWashroom")){
try {
URL url = new URL(get_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
StringBuilder stringBuilder = new StringBuilder();
while ((JSON_STRING = bufferedReader.readLine())!=null) {
stringBuilder.append(JSON_STRING+"\n");
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
//Return JSON formatted info
return stringBuilder.toString().trim();
} catch (MalformedURLException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
if (result.equals("Washroom Added!")) {
Toast.makeText(ctx,result,Toast.LENGTH_LONG).show();
WASHROOMS_LOADED = false;
} else {
//setting result as a movable string
json_string = result;
//intent and sending JSON data
Intent intent = new Intent(ctx,MapsActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("json_data",json_string);
ctx.startActivity(intent);
WASHROOMS_LOADED = true;
}
}
}
If you need anymore of my code, I would be happy to show some more.
You are getting new marker on reopening the app because you are getting database info in your onCreate() method which is triggered only on start of activity. Try getting database info either when location changes or try overriding onNewIntent method. To override onNewIntent first set launchmode of your activity to singleTop in manifest.
i am running a web service with some json data which i use to make markers on my map(this gets updated every hour).i want to add button on my android map so that i will refresh the markers data.any idea without changing much of the structure?should i do something on the threads?or restart the activity?
heres is the code
public class MainActivity extends FragmentActivity {
private static final String LOG_TAG = "jsonmap";
private static final String SERVICE_URL = "http://7a27183e.ngrok.com";
public GoogleMap map;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(activity_maps);
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (map == null) {
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map);
map = mapFragment.getMap();
if (map != null) {
setUpMap();
// new MarkerTask().execute();
}
}
}
private void setUpMap() {
UiSettings settings = map.getUiSettings();
settings.setZoomControlsEnabled(true);
settings.setScrollGesturesEnabled(true);
// Retrieve the city data from the web service
// In a worker thread since it's a network operation.
new Thread(new Runnable() {
public void run() {
try {
retrieveAndAddCities();
} catch (IOException e) {
Log.e(LOG_TAG, "Cannot retrive cities", e);
return;
}
}
}).start();
}
protected void retrieveAndAddCities() throws IOException {
HttpURLConnection conn = null;
final StringBuilder json = new StringBuilder();
try {
// Connect to the web service
URL url = new URL(SERVICE_URL);
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
// Read the JSON data into the StringBuilder
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
json.append(buff, 0, read);
}
} catch (IOException e) {
Log.e(LOG_TAG, "Error connecting to service", e);
throw new IOException("Error connecting to service", e);
} finally {
if (conn != null) {
conn.disconnect();
}
}
// Create markers for the city data.
// Must run this on the UI thread since it's a UI operation.
runOnUiThread(new Runnable() {
public void run() {
try {
createMarkersFromJson(json.toString());
} catch (JSONException e) {
Log.e(LOG_TAG, "Error processing JSON", e);
}
}
});
}
void createMarkersFromJson(String json) throws JSONException {
// De-serialize the JSON string into an array of city objects
JSONArray jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
// Create a marker for each city in the JSON data.
//.title(jsonObj.getString("pollutant")+" "+jsonObj.getString("network"))
// .snippet(Integer.toString(jsonObj.getInt("numeric_val")))
//DATE!!
JSONObject jsonObj = jsonArray.getJSONObject(i);
map.addMarker(new MarkerOptions()
.title(jsonObj.getString("network") + "\n" + jsonObj.getString("date"))
.snippet(jsonObj.getString("pollutant") + "=" + jsonObj.getString("numeric_val"))
.position(new LatLng(
jsonObj.getDouble("x"),
jsonObj.getDouble("y")))
.icon(BitmapDescriptorFactory.defaultMarker(new Random().nextInt(360)))
);
map.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoContents(Marker arg0) {
return null;
}
#Override
public View getInfoWindow(Marker arg0) {
View v = getLayoutInflater().inflate(R.layout.customlayout, null);
TextView tTitle = (TextView) v.findViewById(R.id.title);
TextView tSnippet = (TextView) v.findViewById(R.id.snippet);
tTitle.setText(arg0.getTitle());
tSnippet.setText(arg0.getSnippet());
return v;
}
});
}
}
}
this is the json structure:
https://gist.githubusercontent.com/anonymous/42af315ab003ab01764d/raw/79b6cf5451038bd2e35c376766e9ab44bd385a02/gistfile2.txt
and a screenshot:
http://imgur.com/WZNC9Oz
I have done some modification in your method named createMarkersFromJson() at line map.addMarker(). Now you can use changeMarkerPosition() to change the position of marker.
HashMap<String, Marker> markerHashMap = new HashMap<>();
void changeMarkerPosition(String key, LatLng latLng) {
markerHashMap.get(key).setPosition(latLng);
}
void createMarkersFromJson(String json) throws JSONException {
// De-serialize the JSON string into an array of city objects
JSONArray jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
// Create a marker for each city in the JSON data.
//.title(jsonObj.getString("pollutant")+" "+jsonObj.getString("network"))
// .snippet(Integer.toString(jsonObj.getInt("numeric_val")))
//DATE!!
JSONObject jsonObj = jsonArray.getJSONObject(i);
markerHashMap.put("key"+i,(map.addMarker(new MarkerOptions()
.title(jsonObj.getString("network") + "\n" + jsonObj.getString("date"))
.snippet(jsonObj.getString("pollutant") + "=" + jsonObj.getString("numeric_val"))
.position(new LatLng(
jsonObj.getDouble("x"),
jsonObj.getDouble("y")))
.icon(BitmapDescriptorFactory.defaultMarker(new Random().nextInt(360)))
);)
map.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoContents(Marker arg0) {
return null;
}
#Override
public View getInfoWindow(Marker arg0) {
View v = getLayoutInflater().inflate(R.layout.customlayout, null);
TextView tTitle = (TextView) v.findViewById(R.id.title);
TextView tSnippet = (TextView) v.findViewById(R.id.snippet);
tTitle.setText(arg0.getTitle());
tSnippet.setText(arg0.getSnippet());
return v;
}
});
}
I have a somehow long question. I am now learning about Google Maps API and I am required to make the app get some JSON data from a website, then set some of this data in an info window as the title or whatever.
The important part is that I have to do this with an interface class, whereas the AsyncTask that downloads this data must also be in another class. So I am currently very confused how to make this communication possible, and to have as little code as possible in the AsyncTask class. I also don't understand very well this interface thing.
Please someone help.
So here is the main activity:
package com.example.gmapsexample;
public class MainActivity extends Activity {
private GoogleMap mMap;
Marker marker = null;
HttpClient klient;
String data;
String s;
Double latt, lngg;
GoogleMapOptions options;
String adres = "http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=en&username=sartheris";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
options = new GoogleMapOptions();
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
options.mapType(GoogleMap.MAP_TYPE_SATELLITE).compassEnabled(true).rotateGesturesEnabled(true).tiltGesturesEnabled(true).zoomControlsEnabled(true);
klient = new DefaultHttpClient();
GetJson gg = new GetJson();
gg.execute();
/** On Info Window Click */
mMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker arg0) {
marker.setTitle(s);
Toast.makeText(getApplicationContext(), "Info Window Clicked", Toast.LENGTH_SHORT).show();
}
});
}
}
Here is the GetJson class
package com.example.gmapsexample;
public class GetJson extends AsyncTask<String, Void, String> {
HttpClient klient;
String adres = "http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=en&username=sartheris";
String s;
Double latt, lngg;
private GoogleMap mMap;
Marker marker;
GoogleMapOptions options;
#Override
protected String doInBackground(String... params) {
klient = new DefaultHttpClient();
options = new GoogleMapOptions();
StringBuilder url = new StringBuilder(adres);
HttpGet hg = new HttpGet(url.toString());
HttpResponse hr = null;
try {
hr = klient.execute(hg);
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
int status = hr.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity he = hr.getEntity();
String data = null;
try {
data = EntityUtils.toString(he);
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
JSONObject jsonGet = null;
try {
jsonGet = new JSONObject(data);
} catch (JSONException e1) {
e1.printStackTrace();
}
if (jsonGet.has("geonames")) {
try {
JSONObject arrGet = jsonGet.getJSONArray("geonames").getJSONObject(0);
s = arrGet.getString("toponymName");
latt = arrGet.getDouble("lat");
lngg = arrGet.getDouble("lng");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
marker = new Marker(this);
marker = mMap.addMarker(new MarkerOptions()
.position(new LatLng(latt, lngg))
.title("HELLO WORLD").snippet("BLQ")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
.draggable(true));
}
}
And now I need an interface class that would help with the data passing...
In your main class create an interface:
public interface ParsingCallback{
void onFinishedParsing(MarkerOptions marker);
}
Pass it a copy to your AsyncTask
GetJson gg = new GetJson(new ParsingCallback(){
void onFinishedParsing(MarkerOptions marker) {
mMap.addMarker(marker);
}
);
gg.execute();
In your AsyncTask create the constructor
private ParsingCallback _callback;
public GetJson (ParsingCallback callback){
_callback = callback;
}
And then in your onPostExecute:
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
_callback.onFinishedParsing(new MarkerOptions()
.position(new LatLng(latt, lngg))
.title("HELLO WORLD")
.snippet("BLQ")
);
}
Hope that helps :)