【问题标题】:Android Navigation Drawer displaying empty google mapAndroid 导航抽屉显示空的谷歌地图
【发布时间】:2016-06-30 20:28:10
【问题描述】:

我目前正在开发一款在地图上显示不同内容的 Android 应用。我有一个完美运行的导航抽屉和一些谷歌地图活动,它们返回附近的地方,如餐馆和吃饭的地方。问题是,当我单击旨在打开地图活动的导航抽屉项目时,它会加载基本地图而没有其他任何内容。我想补充一点,地图活动在单独的项目中完美运行。您可以在下面找到我的代码。 NavigationActivity 的代码:

  import android.content.Intent;
  import android.os.Bundle;
  import android.support.v7.app.ActionBarDrawerToggle;
  import android.view.LayoutInflater;
  import android.view.View;
  import android.support.design.widget.NavigationView;
  import android.support.v4.view.GravityCompat;
  import android.support.v4.widget.DrawerLayout;
  import android.support.v7.app.AppCompatActivity;
  import android.support.v7.widget.Toolbar;
  import android.view.Menu;
  import android.view.MenuItem;
  import android.widget.ImageView;
  import android.widget.TextView;

  import com.example.gabrielab.proiectdefinitiv.MainActivity;
  import com.example.gabrielab.proiectdefinitiv.Maps.EatAndDrinkActivity;
  import com.example.gabrielab.proiectdefinitiv.Maps.MuseumActivity;


  import org.json.JSONObject;

public class NavigationActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

JSONObject response, profile_pic_data, profile_pic_url;
TextView user_name, user_email;
ImageView user_picture;
NavigationView navigation_view;
android.support.v4.app.FragmentTransaction fragmentTransaction;
NavigationView navigationView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_navigation);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setTitle("");

    Intent intent = getIntent();
    String jsondata = intent.getStringExtra("jsondata");

    setNavigationHeader();    // call setNavigationHeader Method.
    setUserProfile(jsondata);  // call setUserProfile Method.


    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    navigation_view.setNavigationItemSelectedListener(this);
    navigationView = (NavigationView) findViewById(R.id.nav_view);

}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

/*
    Set Navigation header by using Layout Inflater.
 */

public void setNavigationHeader(){

    navigation_view = (NavigationView) findViewById(R.id.nav_view);

    View header = LayoutInflater.from(this).inflate(R.layout.nav_header_navigation, null);
    navigation_view.addHeaderView(header);

    user_name = (TextView) header.findViewById(R.id.username);
    user_picture = (ImageView) header.findViewById(R.id.profile_pic);
    user_email = (TextView) header.findViewById(R.id.email);
}

public  void  setUserProfile(String jsondata){

    try {
        response = new JSONObject(jsondata);
        user_email.setText(response.get("email").toString());
        user_name.setText(response.get("name").toString());
        profile_pic_data = new JSONObject(response.get("picture").toString());
        profile_pic_url = new JSONObject(profile_pic_data.getString("data"));

        Picasso.with(this).load(profile_pic_url.getString("url"))
                .into(user_picture);

    } catch (Exception e){
        e.printStackTrace();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    //   getMenuInflater().inflate(R.menu.home, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_logout){

        LoginManager.getInstance().logOut();
        Intent intent = new Intent(NavigationActivity.this, MainActivity.class);
        startActivity(intent);
    }  else if (id == R.id.nav_culture) {
        Intent intent = new Intent(NavigationActivity.this, MuseumActivity.class);
        startActivity(intent);

    } else if (id == R.id.nav_eat) {
        Intent intent = new Intent(NavigationActivity.this, EatAndDrinkActivity.class);
        startActivity(intent);
    } else if (id == R.id.nav_coffee) {

    } else if (id == R.id.nav_parks) {

    } else if (id == R.id.nav_shopping) {

    }else if(id==R.id.nav_hospitals){

    }else if(id==R.id.nav_transportation){

    }else if(id==R.id.nav_search){

    }else if(id==R.id.nav_tripplanner){

        Intent intent = new Intent(NavigationActivity.this, RoutingActivity.class);
        startActivity(intent);
    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

}

以及地图活动的代码

 import android.Manifest;
 import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;

import com.example.gabrielab.proiectdefinitiv.R;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MapsEatAndDrink extends AppCompatActivity implements
       GoogleApiClient.ConnectionCallbacks,    GoogleApiClient.OnConnectionFailedListener,
    LocationListener,
    OnMapReadyCallback {
private GoogleMap mGoogleMap;
SupportMapFragment mapFrag;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
LatLng latLng;
double mLatitude = 0;
double mLongitude = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_maps_museum);

    mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
    mapFrag.getMapAsync(this);
}




@Override
public void onMapReady(GoogleMap googleMap) {

    mGoogleMap = googleMap;
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    mGoogleMap.setMyLocationEnabled(true);
    buildGoogleApiClient();
    mGoogleApiClient.connect();
    StringBuilder sbValue = new StringBuilder(sbMethod());
    PlacesTask placesTask = new PlacesTask();
    placesTask.execute(sbValue.toString());
}

@Override
public void onPause()
{
    super.onPause();
    //Unregister for location callbacks:
    if (mGoogleApiClient != null)
    {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
    }
}

protected synchronized void buildGoogleApiClient()
{
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
}

@Override
public void onConnected(Bundle bundle) throws SecurityException
{
    Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
    // Get LocationManager object from System Service LOCATION_SERVICE
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    // Create a criteria object to retrieve provider
    Criteria criteria = new Criteria();
    // Get the name of the best provider
    String provider = locationManager.getBestProvider(criteria, true);
    // Get Current Location
    Location myLocation = locationManager.getLastKnownLocation(provider);
    // Get latitude of the current location
    double latitude = myLocation.getLatitude();
    // Get longitude of the current location
    double longitude = myLocation.getLongitude();
    // Create a LatLng object for the current location
    latLng = new LatLng(latitude, longitude);

    //mGoogleMap.clear();
    //latLng = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
    MarkerOptions markerOptions = new MarkerOptions();
    markerOptions.position(latLng);
    markerOptions.title("Current Position");
    markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
    Marker m = mGoogleMap.addMarker(markerOptions);
    m.showInfoWindow();
    mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(11));
    Toast.makeText(this,"Touch the Pink Markers to view the details of that Hospital",Toast.LENGTH_SHORT).show();
}

@Override
public void onConnectionSuspended(int i) {
    Toast.makeText(this,"onConnectionSuspended",Toast.LENGTH_SHORT).show();
}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    Toast.makeText(this,"onConnectionFailed",Toast.LENGTH_SHORT).show();
}

@Override
public void onLocationChanged(Location location) {

}

public StringBuilder sbMethod() throws SecurityException
{
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    String provider = locationManager.getBestProvider(criteria, true);
    Location myLocation = locationManager.getLastKnownLocation(provider);
    mLatitude=myLocation.getLatitude();
    mLongitude=myLocation.getLongitude();

    StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
    sb.append("location=" + mLatitude + "," + mLongitude);
    sb.append("&radius=40000");
    sb.append("&types=" + "restaurant|meal_delivery|fast_food|bakery|bar|liquor_store|meal_takeaway|");
    sb.append("&sensor=true");

    sb.append("&key=AIzaSyCxSpR3eT4wPPNn-TulLh9Lqk47NBrlOz0");

    Log.d("Map", "url: " + sb.toString());

    return sb;
}

private class PlacesTask extends AsyncTask<String, Integer, String>
{

    String data = null;

    // Invoked by execute() method of this object
    @Override
    protected String doInBackground(String... url) {
        try {
            data = downloadUrl(url[0]);
        } catch (Exception e) {
            Log.d("Background Task", e.toString());
        }
        return data;
    }

    // Executed after the complete execution of doInBackground() method
    @Override
    protected void onPostExecute(String result) {
        ParserTask parserTask = new ParserTask();

        // Start parsing the Google places in JSON format
        // Invokes the "doInBackground()" method of the class ParserTask
        parserTask.execute(result);
    }
}

private String downloadUrl(String strUrl) throws IOException
{
    String data = "";
    InputStream iStream = null;
    HttpURLConnection urlConnection = null;
    try {
        URL url = new URL(strUrl);

        // Creating an http connection to communicate with url
        urlConnection = (HttpURLConnection) url.openConnection();

        // Connecting to url
        urlConnection.connect();

        // Reading data from url
        iStream = urlConnection.getInputStream();

        BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

        StringBuffer sb = new StringBuffer();

        String line = "";
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }

        data = sb.toString();

        br.close();

    } catch (Exception e) {
        Log.d("Exception", e.toString());
    } finally {
        iStream.close();
        urlConnection.disconnect();
    }
    return data;
}

private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String, String>>> {

    JSONObject jObject;

    // Invoked by execute() method of this object
    @Override
    protected List<HashMap<String, String>> doInBackground(String... jsonData) {

        List<HashMap<String, String>> places = null;
        Place_JSON placeJson = new Place_JSON();

        try {
            jObject = new JSONObject(jsonData[0]);

            places = placeJson.parse(jObject);

        } catch (Exception e) {
            Log.d("Exception", e.toString());
        }
        return places;
    }

    // Executed after the complete execution of doInBackground() method
    @Override
    protected void onPostExecute(List<HashMap<String, String>> list) {

        Log.d("Map", "list size: " + list.size());
        // Clears all the existing markers;
        //mGoogleMap.clear();

        for (int i = 0; i < list.size(); i++) {

            // Creating a marker
            MarkerOptions markerOptions = new MarkerOptions();

            // Getting a place from the places list
            HashMap<String, String> hmPlace = list.get(i);


            // Getting latitude of the place
            double lat = Double.parseDouble(hmPlace.get("lat"));

            // Getting longitude of the place
            double lng = Double.parseDouble(hmPlace.get("lng"));

            // Getting name
            String name = hmPlace.get("place_name");

            Log.d("Map", "place: " + name);

            // Getting vicinity
            String vicinity = hmPlace.get("vicinity");

            latLng = new LatLng(lat, lng);

            // Setting the position for the marker
            markerOptions.position(latLng);

            markerOptions.title(name + " : " + vicinity);

            markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));

            // Placing a marker on the touched position
            Marker m = mGoogleMap.addMarker(markerOptions);
        }
    }
}
public class Place_JSON {

    /**
     * Receives a JSONObject and returns a list
     */
    public List<HashMap<String, String>> parse(JSONObject jObject) {

        JSONArray jPlaces = null;
        try {
            /** Retrieves all the elements in the 'places' array */
            jPlaces = jObject.getJSONArray("results");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        /** Invoking getPlaces with the array of json object
         * where each json object represent a place
         */
        return getPlaces(jPlaces);
    }

    private List<HashMap<String, String>> getPlaces(JSONArray jPlaces) {
        int placesCount = jPlaces.length();
        List<HashMap<String, String>> placesList = new ArrayList<HashMap<String, String>>();
        HashMap<String, String> place = null;

        /** Taking each place, parses and adds to list object */
        for (int i = 0; i < placesCount; i++) {
            try {
                /** Call getPlace with place JSON object to parse the place */
                place = getPlace((JSONObject) jPlaces.get(i));
                placesList.add(place);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return placesList;
    }

    /**
     * Parsing the Place JSON object
     */
    private HashMap<String, String> getPlace(JSONObject jPlace)
    {

        HashMap<String, String> place = new HashMap<String, String>();
        String placeName = "-NA-";
        String vicinity = "-NA-";
        String latitude = "";
        String longitude = "";
        String reference = "";

        try {
            // Extracting Place name, if available
            if (!jPlace.isNull("name")) {
                placeName = jPlace.getString("name");
            }

            // Extracting Place Vicinity, if available
            if (!jPlace.isNull("vicinity")) {
                vicinity = jPlace.getString("vicinity");
            }

            latitude = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lat");
            longitude = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lng");
            reference = jPlace.getString("reference");

            place.put("place_name", placeName);
            place.put("vicinity", vicinity);
            place.put("lat", latitude);
            place.put("lng", longitude);
            place.put("reference", reference);

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return place;
    }
}

}

我知道导航抽屉更适用于片段,但我想不出一个正确的方法来将我的地图活动变成片段而不丢失任何功能。任何建议都是有帮助的。提前谢谢你!

【问题讨论】:

    标签: android google-maps google-places-api navigation-drawer


    【解决方案1】:

    如今,您绝对需要将 Fragments 与 NavigationDrawer 一起使用。

    至于将您的 Map Activity 转换为 Fragment,这并不难。

    我刚刚为您做了一个快速转换,请注意它现在扩展了 SupportMapFragment 而不是 AppCompatActivity。 另请注意,它不需要膨胀任何布局 xml,甚至不需要 onCreate()onCreateView() 覆盖。 只需从onResume() 覆盖调用getMapAsync()。 此外,无论您在何处使用this 作为上下文,只需将其替换为getActivity()

    这是修改后的类代码:

    public class MapsEatAndDrink extends SupportMapFragment implements
            GoogleApiClient.ConnectionCallbacks,    GoogleApiClient.OnConnectionFailedListener,
            LocationListener,
            OnMapReadyCallback {
        //.......
    
        @Override
        public void onResume() {
            super.onResume();
            getMapAsync(this);
        }
    
        @Override
        public void onMapReady(GoogleMap googleMap) {
    
           mGoogleMap = googleMap;
           if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
               // TODO: Consider calling
               //    ActivityCompat#requestPermissions
               // here to request the missing permissions, and then overriding
               //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
               //                                          int[] grantResults)
               // to handle the case where the user grants the permission. See the documentation
               // for ActivityCompat#requestPermissions for more details.
               return;
           }
           mGoogleMap.setMyLocationEnabled(true);
           buildGoogleApiClient();
           mGoogleApiClient.connect();
           StringBuilder sbValue = new StringBuilder(sbMethod());
           PlacesTask placesTask = new PlacesTask();
           placesTask.execute(sbValue.toString());
        }
    
        @Override
        public void onPause()
        {
           super.onPause();
           //Unregister for location callbacks:
           if (mGoogleApiClient != null)
           {
               LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
           }
        }
    
        protected synchronized void buildGoogleApiClient()
        {
           mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
                   .addConnectionCallbacks(this)
                   .addOnConnectionFailedListener(this)
                   .addApi(LocationServices.API)
                   .build();
        }
    
        @Override
        public void onConnected(Bundle bundle) throws SecurityException
        {
           Toast.makeText(getActivity(), "Connected", Toast.LENGTH_SHORT).show();
           // Get LocationManager object from System Service LOCATION_SERVICE
           LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
           // Create a criteria object to retrieve provider
           Criteria criteria = new Criteria();
           // Get the name of the best provider
           String provider = locationManager.getBestProvider(criteria, true);
           // Get Current Location
           Location myLocation = locationManager.getLastKnownLocation(provider);
           // Get latitude of the current location
           double latitude = myLocation.getLatitude();
           // Get longitude of the current location
           double longitude = myLocation.getLongitude();
           // Create a LatLng object for the current location
           latLng = new LatLng(latitude, longitude);
    
           //mGoogleMap.clear();
           //latLng = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
           MarkerOptions markerOptions = new MarkerOptions();
           markerOptions.position(latLng);
           markerOptions.title("Current Position");
           markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
           Marker m = mGoogleMap.addMarker(markerOptions);
           m.showInfoWindow();
           mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
           mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(11));
           Toast.makeText(this,"Touch the Pink Markers to view the details of that Hospital",Toast.LENGTH_SHORT).show();
        }
    
        @Override
        public void onConnectionSuspended(int i) {
           Toast.makeText(getActivity(),"onConnectionSuspended",Toast.LENGTH_SHORT).show();
        }
    
        @Override
        public void onConnectionFailed(ConnectionResult connectionResult) {
           Toast.makeText(getActivity(),"onConnectionFailed",Toast.LENGTH_SHORT).show();
        }
    
        @Override
        public void onLocationChanged(Location location) {
    
        }
    
        public StringBuilder sbMethod() throws SecurityException
        {
           LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
           Criteria criteria = new Criteria();
           String provider = locationManager.getBestProvider(criteria, true);
           Location myLocation = locationManager.getLastKnownLocation(provider);
           mLatitude=myLocation.getLatitude();
           mLongitude=myLocation.getLongitude();
    
           StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
           sb.append("location=" + mLatitude + "," + mLongitude);
           sb.append("&radius=40000");
           sb.append("&types=" + "restaurant|meal_delivery|fast_food|bakery|bar|liquor_store|meal_takeaway|");
           sb.append("&sensor=true");
    
           sb.append("&key=AIzaSyCxSpR3eT4wPPNn-TulLh9Lqk47NBrlOz0");
    
           Log.d("Map", "url: " + sb.toString());
    
           return sb;
        }
    
        private class PlacesTask extends AsyncTask<String, Integer, String>
        {
    
           String data = null;
    
           // Invoked by execute() method of this object
           @Override
           protected String doInBackground(String... url) {
               try {
                   data = downloadUrl(url[0]);
               } catch (Exception e) {
                   Log.d("Background Task", e.toString());
               }
               return data;
           }
    
           // Executed after the complete execution of doInBackground() method
           @Override
           protected void onPostExecute(String result) {
               ParserTask parserTask = new ParserTask();
    
               // Start parsing the Google places in JSON format
               // Invokes the "doInBackground()" method of the class ParserTask
               parserTask.execute(result);
           }
        }
    
        private String downloadUrl(String strUrl) throws IOException
        {
           String data = "";
           InputStream iStream = null;
           HttpURLConnection urlConnection = null;
           try {
               URL url = new URL(strUrl);
    
               // Creating an http connection to communicate with url
               urlConnection = (HttpURLConnection) url.openConnection();
    
               // Connecting to url
               urlConnection.connect();
    
               // Reading data from url
               iStream = urlConnection.getInputStream();
    
               BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
    
               StringBuffer sb = new StringBuffer();
    
               String line = "";
               while ((line = br.readLine()) != null) {
                   sb.append(line);
               }
    
               data = sb.toString();
    
               br.close();
    
           } catch (Exception e) {
               Log.d("Exception", e.toString());
           } finally {
               iStream.close();
               urlConnection.disconnect();
           }
           return data;
        }
    
        private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String, String>>> {
    
           JSONObject jObject;
    
           // Invoked by execute() method of this object
           @Override
           protected List<HashMap<String, String>> doInBackground(String... jsonData) {
    
               List<HashMap<String, String>> places = null;
               Place_JSON placeJson = new Place_JSON();
    
               try {
                   jObject = new JSONObject(jsonData[0]);
    
                   places = placeJson.parse(jObject);
    
               } catch (Exception e) {
                   Log.d("Exception", e.toString());
               }
               return places;
           }
    
           // Executed after the complete execution of doInBackground() method
           @Override
           protected void onPostExecute(List<HashMap<String, String>> list) {
    
               Log.d("Map", "list size: " + list.size());
               // Clears all the existing markers;
               //mGoogleMap.clear();
    
               for (int i = 0; i < list.size(); i++) {
    
                   // Creating a marker
                   MarkerOptions markerOptions = new MarkerOptions();
    
                   // Getting a place from the places list
                   HashMap<String, String> hmPlace = list.get(i);
    
    
                   // Getting latitude of the place
                   double lat = Double.parseDouble(hmPlace.get("lat"));
    
                   // Getting longitude of the place
                   double lng = Double.parseDouble(hmPlace.get("lng"));
    
                   // Getting name
                   String name = hmPlace.get("place_name");
    
                   Log.d("Map", "place: " + name);
    
                   // Getting vicinity
                   String vicinity = hmPlace.get("vicinity");
    
                   latLng = new LatLng(lat, lng);
    
                   // Setting the position for the marker
                   markerOptions.position(latLng);
    
                   markerOptions.title(name + " : " + vicinity);
    
                   markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
    
                   // Placing a marker on the touched position
                   Marker m = mGoogleMap.addMarker(markerOptions);
               }
           }
        }
        public class Place_JSON {
    
           /**
            * Receives a JSONObject and returns a list
            */
           public List<HashMap<String, String>> parse(JSONObject jObject) {
    
               JSONArray jPlaces = null;
               try {
                   /** Retrieves all the elements in the 'places' array */
                   jPlaces = jObject.getJSONArray("results");
               } catch (JSONException e) {
                   e.printStackTrace();
               }
               /** Invoking getPlaces with the array of json object
                * where each json object represent a place
                */
               return getPlaces(jPlaces);
           }
    
           private List<HashMap<String, String>> getPlaces(JSONArray jPlaces) {
               int placesCount = jPlaces.length();
               List<HashMap<String, String>> placesList = new ArrayList<HashMap<String, String>>();
               HashMap<String, String> place = null;
    
               /** Taking each place, parses and adds to list object */
               for (int i = 0; i < placesCount; i++) {
                   try {
                       /** Call getPlace with place JSON object to parse the place */
                       place = getPlace((JSONObject) jPlaces.get(i));
                       placesList.add(place);
                   } catch (JSONException e) {
                       e.printStackTrace();
                   }
               }
               return placesList;
           }
    
           /**
            * Parsing the Place JSON object
            */
           private HashMap<String, String> getPlace(JSONObject jPlace)
           {
    
               HashMap<String, String> place = new HashMap<String, String>();
               String placeName = "-NA-";
               String vicinity = "-NA-";
               String latitude = "";
               String longitude = "";
               String reference = "";
    
               try {
                   // Extracting Place name, if available
                   if (!jPlace.isNull("name")) {
                       placeName = jPlace.getString("name");
                   }
    
                   // Extracting Place Vicinity, if available
                   if (!jPlace.isNull("vicinity")) {
                       vicinity = jPlace.getString("vicinity");
                   }
    
                   latitude = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lat");
                   longitude = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lng");
                   reference = jPlace.getString("reference");
    
                   place.put("place_name", placeName);
                   place.put("vicinity", vicinity);
                   place.put("lat", latitude);
                   place.put("lng", longitude);
                   place.put("reference", reference);
    
               } catch (JSONException e) {
                   e.printStackTrace();
               }
               return place;
           }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-21
      • 1970-01-01
      相关资源
      最近更新 更多