2014-06-23 7 views
0

У меня была проблема, что geocoder.ispresent() всегда возвращает false. Я googled для решения и обнаружил, что служба карты google не включена. Как мы можем включить эту услугу? Может ли кто-нибудь вести меня?Как включить службу карты google

package com.incv.mobile.freejscf; 

import java.io.IOException; 
import java.util.List; 
import java.util.Locale; 
import android.app.Application; 
import android.content.Context; 
import android.location.Address; 
import android.location.Geocoder; 
import android.location.Location; 
import android.location.LocationListener; 
import android.location.LocationManager; 
import android.os.AsyncTask; 
import android.os.Build; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 


public class MyApplication extends Application implements LocationListener { 
    double latitude = 0; 
    double longitude = 0; 
    @Override 
    public void onCreate() { 
     super.onCreate();  
     Location mLocation = null; 
     if (Geocoder.isPresent()) { 
       (new GetAddressTask(this)).execute(mLocation); 
      } 
     else{ 
      Log.e("Not", "Geocoder is not present"); 
     } 

    } 

    private class GetAddressTask extends 
    AsyncTask<Location, Void, String> { 
    Context mContext; 
    public GetAddressTask(Context context) { 
     super(); 
     mContext = context; 
    } 

    /** 
    * Get a Geocoder instance, get the latitude and longitude 
    * look up the address, and return it 
    * 
    * @params params One or more Location objects 
    * @return A string containing the address of the current 
    * location, or an empty string if no address can be found, 
    * or an error message 
    */ 
    @Override 
    protected String doInBackground(Location... params) { 
     Geocoder geocoder = 
       new Geocoder(mContext, Locale.getDefault()); 
     // Get the current location from the input parameter list 
     Location loc = params[0]; 
     // Create a list to contain the result address 
     List<Address> addresses = null; 
     try { 
      /* 
      * Return 1 address. 
      */ 
      addresses = geocoder.getFromLocation(loc.getLatitude(), 
        loc.getLongitude(), 1); 
     } catch (IOException e1) { 
     Log.e("LocationSampleActivity", 
       "IO Exception in getFromLocation()"); 
     e1.printStackTrace(); 
     return ("IO Exception trying to get address"); 
     } catch (IllegalArgumentException e2) { 
     // Error message to post in the log 
     String errorString = "Illegal arguments " + 
       Double.toString(loc.getLatitude()) + 
       " , " + 
       Double.toString(loc.getLongitude()) + 
       " passed to address service"; 
     Log.e("LocationSampleActivity", errorString); 
     e2.printStackTrace(); 
     return errorString; 
     } 
     // If the reverse geocode returned an address 
     if (addresses != null && addresses.size() > 0) { 
      // Get the first address 
      Address address = addresses.get(0); 
      /* 
      * Format the first line of address (if available), 
      * city, and country name. 
      */ 
      String addressText = String.format(
        "%s, %s, %s", 
        // If there's a street address, add it 
        address.getMaxAddressLineIndex() > 0 ? 
          address.getAddressLine(0) : "", 
        // Locality is usually a city 
        address.getLocality(), 
        // The country of the address 
        address.getCountryName()); 
      // Return the text 
      return addressText; 
     } else { 
      return "No address found"; 
     } 
    } 
    protected void onPostExecute(String address) { 
     // mAddress.setText(address); 
     Log.e("Address", address.toString()); 
    } 

    } 
    public void getAddress(View v) { 
    // Ensure that a Geocoder services is available 

    } 
    @Override 
    public void onLocationChanged(Location arg0) { 
     // TODO Auto-generated method stub 

    } 
    @Override 
    public void onProviderDisabled(String provider) { 
     // TODO Auto-generated method stub 

    } 
    @Override 
    public void onProviderEnabled(String provider) { 
     // TODO Auto-generated method stub 

    } 
    @Override 
    public void onStatusChanged(String provider, int status, Bundle extras) { 
     // TODO Auto-generated method stub 

    } 
} 

В приведенном выше коде вначале onCreate methid получить исполнение. но он всегда переходит в другую часть. Это означает, что GeoCoder.isProvider() возвращает false.

+0

Адрес электронной почты: Остальное Код? Как вы получаете геокодер и завершили ли вы все шаги руководства разработчика по API геокодирования? –

+0

@lvan ok i все отправляют код. –

+0

Вы используете это на устройстве или эмуляторе? Кроме того, если вы прокомментируете условие и выполните задачу, независимо от того, что возвращает 'isPresent()', остальная часть кода завершится с ошибкой в ​​какой-то момент? –

ответ

0

Просто следуйте инструкциям разработчиков по настройке карты в приложениях для Android. Ниже приводится краткое руководство линии

  1. Загрузите Google playservices от менеджера Android SDK
  2. Добавить это затмение и добавить в библиотеку для проекта
  3. Добавьте ключи и другие prerequisties внутри Google консоли
  4. введите необходимые разрешения и ключи для AndroidManifest.xml
Смежные вопросы