2017-12-25 4 views
0

기기의 현재 위치에서 위도와 경도를 읽고이 데이터를 사용하여 maps.googleapis.com에서 정보를 검색하려고합니다. 위도 및 경도 값을 onConnected() 메서드 외부에서 사용할 수없는 경우 사용자 위치를 올바르게 찾을 수 있습니다.Google API를 사용하여 onConnected() 메소드에서 경도와 위도를 검색하는 방법

나는 ListLoc 클래스의 맨 위에서 URL 문자열을 decleared.

내가 GetContacts에서 url을 (읽으려고

) 클래스 :

public String url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location="+latitude+","+longitude+"&radius=1500&type=restaurant&key=my_key";

위도와 경도는 항상 NULL이다.

내 문제를 해결하는 방법에 대한 제안 사항을 제공해 주시겠습니까? 전역 변수를 사용하려고했지만 문제를 해결하지 못했습니다.

이 내 전체 코드입니다 :

import ... 


public class ListLoc extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener { 


    public Double latitude=0.0, longitude =0.0; 
    private TextView mLatitudeTextView; 
    private TextView mLongitudeTextView; 
    private TextView mTextView, mTextView2; 
    private GoogleApiClient mGoogleApiClient; 
    private Location mLocation; 
    private LocationManager mLocationManager; 


    private LocationRequest mLocationRequest; 
    private com.google.android.gms.location.LocationListener listener; 
    private long UPDATE_INTERVAL = 2 * 1000; /* 10 secs */ 
    private long FASTEST_INTERVAL = 2000; /* 2 sec */ 

    private LocationManager locationManager; 


    private String TAG = ListLoc.class.getSimpleName(); 

    private ProgressDialog pDialog; 
    private ListView lv; 


    // URL to get contacts JSON 
    public String url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location="+latitude+","+longitude+"&radius=1500&type=restaurant&key=my_key"; 


    ArrayList<HashMap<String, String>> contactList; 


    // this functions are specified in the list_item.xml layout file 
    public void onClick_name(View v) { 
     TextView testo = (TextView) findViewById(R.id.textView3); 
     testo.setText("text"); 
    } 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_list_loc); 

     contactList = new ArrayList<>(); 

     lv = (ListView) findViewById(R.id.list); 

     new GetContacts().execute(); 

     mGoogleApiClient = new GoogleApiClient.Builder(this) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this) 
       .addApi(LocationServices.API) 
       .build(); 

     mLocationManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE); 

     checkLocation(); //check whether location service is enable or not in your phone 



    } 

     @Override 
    public void onConnected(Bundle bundle) { 
     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; 
     } 

     startLocationUpdates(); 

     mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); 

     if(mLocation == null){ 
      startLocationUpdates(); 
     } 
     if (mLocation != null) { 

      latitude = mLocation.getLatitude(); 
      longitude = mLocation.getLongitude(); 

      // mLatitudeTextView.setText(String.valueOf(mLocation.getLatitude())); 
      //mLongitudeTextView.setText(String.valueOf(mLocation.getLongitude())); 


     } else { 
      Toast.makeText(this, "Location not Detected", Toast.LENGTH_SHORT).show(); 
     } 
    } 

    @Override 
    public void onConnectionSuspended(int i) { 
     Log.i(TAG, "Connection Suspended"); 
     mGoogleApiClient.connect(); 
    } 

    @Override 
    public void onConnectionFailed(ConnectionResult connectionResult) { 
     Log.i(TAG, "Connection failed. Error: " + connectionResult.getErrorCode()); 
    } 

    @Override 
    protected void onStart() { 
     super.onStart(); 
     if (mGoogleApiClient != null) { 
      mGoogleApiClient.connect(); 
     } 
    } 

    @Override 
    protected void onStop() { 
     super.onStop(); 
     if (mGoogleApiClient.isConnected()) { 
      mGoogleApiClient.disconnect(); 
     } 
    } 

    protected void startLocationUpdates() { 
     // Create the location request 
     mLocationRequest = LocationRequest.create() 
       .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY) 
       .setInterval(UPDATE_INTERVAL) 
       .setFastestInterval(FASTEST_INTERVAL); 
     // Request location updates 
     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; 
     } 
     LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, 
       mLocationRequest, this); 
     Log.d("reque", "--->>>>"); 
    } 

    @Override 
    public void onLocationChanged(Location location) { 

     String msg = "Updated Location: " + 
       Double.toString(location.getLatitude()) + "," + 
       Double.toString(location.getLongitude()); 

     Toast.makeText(this, msg, Toast.LENGTH_SHORT).show(); 
     // You can now create a LatLng Object for use with maps 
     LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude()); 


     // Instantiate the RequestQueue. 


    } 

    private boolean checkLocation() { 
     if(!isLocationEnabled()) 
      showAlert(); 
     return isLocationEnabled(); 
    } 

    private void showAlert() { 
     final AlertDialog.Builder dialog = new AlertDialog.Builder(this); 
     dialog.setTitle("Enable Location") 
       .setMessage("Your Locations Settings is set to 'Off'.\nPlease Enable Location to " + 
         "use this app") 
       .setPositiveButton("Location Settings", new DialogInterface.OnClickListener() { 
        @Override 
        public void onClick(DialogInterface paramDialogInterface, int paramInt) { 

         Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
         startActivity(myIntent); 
        } 
       }) 
       .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
        @Override 
        public void onClick(DialogInterface paramDialogInterface, int paramInt) { 

        } 
       }); 
     dialog.show(); 
    } 

    private boolean isLocationEnabled() { 
     locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
     return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || 
       locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); 
    } 


    /** 
    * Async task class to get json by making HTTP call 
    */ 
    private class GetContacts extends AsyncTask<Void, Void, Void> { 

     ListLoc prova = new ListLoc(); 

     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      // Showing progress dialog 
      pDialog = new ProgressDialog(ListLoc.this); 
      pDialog.setMessage("Please wait..."); 
      pDialog.setCancelable(false); 
      pDialog.show(); 

     } 

     @Override 
     protected Void doInBackground(Void... arg0) { 
      HttpHandler sh = new HttpHandler(); 

      // Making a request to url and getting response 
      String jsonStr = sh.makeServiceCall(prova.url); 


      Log.e(TAG, "Response from url: " + jsonStr); 

      if (jsonStr != null) { 
       try { 
        JSONObject jsonObj = new JSONObject(jsonStr); 

        // Getting JSON Array node 
        JSONArray contacts = jsonObj.getJSONArray("results"); 

        // looping through All Contacts 
        for (int i = 0; i < contacts.length(); i++) { 
         JSONObject c = contacts.getJSONObject(i); 

         String icon = c.getString("icon"); 
         String id = c.getString("id"); 
         String name = c.getString("name"); 



         // tmp hash map for single contact 
         HashMap<String, String> contact = new HashMap<>(); 

         // adding each child node to HashMap key => value 
         // contact.put("id", id); 
         contact.put("name", name); 
         // contact.put("email", icon); 


         // adding contact to contact list 
         contactList.add(contact); 
        } 
       } catch (final JSONException e) { 
        Log.e(TAG, "Json parsing error: " + e.getMessage()); 
        runOnUiThread(new Runnable() { 
         @Override 
         public void run() { 
          Toast.makeText(getApplicationContext(), 
            "Json parsing error: " + e.getMessage(), 
            Toast.LENGTH_LONG) 
            .show(); 
         } 
        }); 

       } 
      } else { 
       Log.e(TAG, "Couldn't get json from server."); 
       runOnUiThread(new Runnable() { 
        @Override 
        public void run() { 
         Toast.makeText(getApplicationContext(), 
           "Couldn't get json from server. Check LogCat for possible errors!", 
           Toast.LENGTH_LONG) 
           .show(); 
        } 
       }); 

      } 

      return null; 
     } 

     @Override 
     protected void onPostExecute(Void result) { 
      super.onPostExecute(result); 
      // Dismiss the progress dialog 
      if (pDialog.isShowing()) 
       pDialog.dismiss(); 
      /** 
      * Updating parsed JSON data into ListView 
      * */ 
      ListAdapter adapter = new SimpleAdapter(
        ListLoc.this, contactList, 
        R.layout.list_item, new String[]{"name"}, new int[]{R.id.name}); 

      lv.setAdapter(adapter); 
     } 

    } 


} 

답변

1

상단에 String url, locationlatitude를 선언 0.0 및 URL이 이미 그 값을 사용하여 설정됩니다. 이 작업을 수행하려면 String url 선언을 doInBackground 방법으로 이동하십시오.

관련 문제