1

현재지도에서 다른 것들을 보여주는 Android 앱을 개발 중입니다. 나는 완벽하게 작동하는 내비게이션 서랍과 음식점 및 먹을 장소와 같은 가까운 장소를 반환하는 일부 Google지도 활동이 있습니다. 문제는지도 활동을 열기위한 탐색 창 항목을 클릭하면 기본지도 만로드된다는 것입니다. 맵 액티비티가 별도의 프로젝트에서 완벽하게 작동한다고 덧붙이고 싶습니다. 아래에서 내 코드를 찾을 수 있습니다. NavigationActivity의 코드 :안드로이드 내비게이션 서랍 빈 Google지도 표시

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

}

내가 탐색 서랍 조각으로 잘 작동하는지 알고 있지만 내가 나오지 않았어에 대한 코드 기능을 잃지 않고 내지도 활동을 조각으로 바꾸는 올바른 방법을 찾지 못했습니다. 조언이 도움이됩니다. 미리 감사드립니다.

답변

0

요즘에는 절대적으로 NavigationDrawer와 함께 Fragments를 사용해야합니다.

맵 활동을 조각으로 변환하는 것은 그리 어렵지 않습니다.

방금 ​​당신을 위해 빠른 변환을했는데, 이제 AppCompatActivity 대신 SupportMapFragment를 확장합니다. 또한 레이아웃 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; 
     } 
    } 
} 
+0

가 대단히 감사합니다! –