Java 在“地图中的搜索位置”活动中自动完成

Java 在“地图中的搜索位置”活动中自动完成,java,android,google-maps,google-places-api,Java,Android,Google Maps,Google Places Api,嗨,我正在学习这个教程 MapsActivity.java public class MapsActivity extends FragmentActivity { private GoogleMap mMap; // Might be null if Google Play services APK is not available. AutoCompleteTextView atvPlaces; PlacesTask placesTask; ParserTask parserTask;

嗨,我正在学习这个教程

MapsActivity.java

public class MapsActivity extends FragmentActivity {

private GoogleMap mMap; // Might be null if Google Play services APK is not available.
AutoCompleteTextView atvPlaces;
PlacesTask placesTask;
ParserTask parserTask;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    atvPlaces = (AutoCompleteTextView) findViewById(R.id.atv_places);
    atvPlaces.setThreshold(1);

    atvPlaces.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            placesTask = new PlacesTask();
            placesTask.execute(s.toString());
        }

        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            // TODO Auto-generated method stub
        }

        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub
        }
    });
    atvPlaces.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            atvPlaces.showDropDown();
            return false;
        }
    });
    setUpMapIfNeeded();
}
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 while downloading url", e.toString());
    }finally{
        iStream.close();
        urlConnection.disconnect();
    }
    return data;
}

// Fetches all places from GooglePlaces AutoComplete Web Service
private class PlacesTask extends AsyncTask<String, Void, String>{

    @Override
    protected String doInBackground(String... place) {
        // For storing data from web service
        String data = "";

        // Obtain browser key from https://code.google.com/apis/console
        String key = "key=My Browser Key";

        String input="";

        try {
            input = "input=" + URLEncoder.encode(place[0], "utf-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }

        // place type to be searched
        String types = "types=geocode";

        // Sensor enabled
        String sensor = "sensor=false";

        // Building the parameters to the web service
        String parameters = input+"&"+types+"&"+sensor+"&"+key;

        // Output format
        String output = "json";

        // Building the url to the web service
        String url = "https://maps.googleapis.com/maps/api/place/autocomplete/"+output+"?"+parameters;

        try{
            // Fetching the data from we service
            data = downloadUrl(url);
        }catch(Exception e){
            Log.d("Background Task",e.toString());
        }
        return data;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        // Creating ParserTask
        parserTask = new ParserTask();

        // Starting Parsing the JSON string returned by Web Service
        parserTask.execute(result);
    }
}
/** A class to parse the Google Places in JSON format */
private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String,String>>>{

    JSONObject jObject;

    @Override
    protected List<HashMap<String, String>> doInBackground(String... jsonData) {

        List<HashMap<String, String>> places = null;

        PlaceJSONParser placeJsonParser = new PlaceJSONParser();

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

            // Getting the parsed data as a List construct
            places = placeJsonParser.parse(jObject);

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

    @Override
    protected void onPostExecute(List<HashMap<String, String>> result) {

        String[] from = new String[] { "description"};
        int[] to = new int[] { android.R.id.text1 };

        // Creating a SimpleAdapter for the AutoCompleteTextView
        SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), result, android.R.layout.simple_list_item_1, from, to);

        // Setting the adapter
        atvPlaces.setAdapter(adapter);
    }
}

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


public void onSearch(View view){
    String location = atvPlaces.getText().toString();

    List<Address> addressList = null;

    if(location!=null || location.equals("")){

        Geocoder geocoder = new Geocoder(this);
        try {
            addressList = geocoder.getFromLocationName(location, 1);
        } catch (IOException e) {
            e.printStackTrace();
        }

        Address address = addressList.get(0);
        LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
        mMap.addMarker(new MarkerOptions().position(latLng).title("Marker"));
        mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
    }
}

public void changeType(View view){
    if(mMap.getMapType() == GoogleMap.MAP_TYPE_NORMAL){
        mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
    }
    else{
        mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    }
}

private void setUpMapIfNeeded() {
    // Do a null check to confirm that we have not already instantiated the map.
    if (mMap == null) {
        // Try to obtain the map from the SupportMapFragment.
        mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                .getMap();
        // Check if we were successful in obtaining the map.
        if (mMap != null) {
            setUpMap();
        }
    }
}

private void setUpMap() {
    mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
    mMap.setMyLocationEnabled(true);
}
}
公共类映射活动扩展了FragmentActivity{
私有GoogleMap mMap;//如果Google Play services APK不可用,则可能为空。
自动完成文本视图;
PlacesTask PlacesTask;
ParserTask ParserTask;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_映射);
atvPlaces=(自动完成文本视图)findViewById(R.id.atv_位置);
atvPlaces.设置阈值(1);
addTextChangedListener(新的TextWatcher(){
@凌驾
public void onTextChanged(字符序列、int start、int before、int count){
placesTask=新的placesTask();
execute(s.toString());
}
更改前的公共无效(字符序列、整数开始、整数计数、,
整数后){
//TODO自动生成的方法存根
}
公共无效后文本已更改(可编辑){
//TODO自动生成的方法存根
}
});
atvPlaces.setOnTouchListener(新视图.OnTouchListener(){
@凌驾
公共布尔onTouch(视图v,运动事件){
atvPlaces.showDropDown();
返回false;
}
});
setupmapifneed();
}
私有字符串下载URL(字符串strUrl)引发IOException{
字符串数据=”;
InputStream iStream=null;
HttpURLConnection-urlConnection=null;
试一试{
URL=新URL(strUrl);
//创建http连接以与url通信
urlConnection=(HttpURLConnection)url.openConnection();
//连接到url
urlConnection.connect();
//从url读取数据
iStream=urlConnection.getInputStream();
BufferedReader br=新的BufferedReader(新的InputStreamReader(iStream));
StringBuffer sb=新的StringBuffer();
字符串行=”;
而((line=br.readLine())!=null){
某人附加(行);
}
data=sb.toString();
br.close();
}捕获(例外e){
Log.d(“下载url时出现异常”,例如toString());
}最后{
iStream.close();
urlConnection.disconnect();
}
返回数据;
}
//从GooglePlaces自动完成Web服务获取所有位置
私有类PlacesTask扩展异步任务{
@凌驾
受保护的字符串背景(字符串…位置){
//用于存储来自web服务的数据
字符串数据=”;
//从中获取浏览器密钥https://code.google.com/apis/console
String key=“key=My Browser key”;
字符串输入=”;
试一试{
input=“input=“+URLEncoder.encode(位置[0],“utf-8”);
}捕获(不支持DencodingException e1){
e1.printStackTrace();
}
//要搜索的位置类型
String types=“types=geocode”;
//传感器启用
字符串sensor=“sensor=false”;
//为web服务构建参数
字符串参数=输入+“&”+类型+“&”+传感器+“&”+键;
//输出格式
字符串输出=“json”;
//构建web服务的url
字符串url=”https://maps.googleapis.com/maps/api/place/autocomplete/“+输出+”?“+参数;
试一试{
//从we服务获取数据
数据=下载url(url);
}捕获(例外e){
Log.d(“后台任务”,例如toString());
}
返回数据;
}
@凌驾
受保护的void onPostExecute(字符串结果){
super.onPostExecute(结果);
//创建ParserTask
parserTask=新的parserTask();
//开始解析Web服务返回的JSON字符串
执行(结果);
}
}
/**以JSON格式解析GooglePlaces的类*/
私有类ParserTask扩展了AsyncTask{
JSONObject jObject;
@凌驾
受保护列表doInBackground(字符串…jsonData){
列表位置=空;
PlaceJSONParser PlaceJSONParser=新的PlaceJSONParser();
试一试{
jObject=新的JSONObject(jsonData[0]);
//将解析后的数据作为列表构造获取
places=placeJsonParser.parse(jObject);
}捕获(例外e){
Log.d(“异常”,例如toString());
}
返回地点;
}
@凌驾
受保护的void onPostExecute(列表结果){
String[]from=新字符串[]{“description”};
int[]to=newint[]{android.R.id.text1};
//为AutoCompleteTextView创建SimpleAdapter
SimpleAdapter=new SimpleAdapter(getBaseContext(),result,android.R.layout.simple\u list\u item\u 1,from,to);
//设置适配器
atvPlaces.setAdapter(适配器);
}
}
@凌驾
公共布尔onCreateOptions菜单(菜单){
//为菜单充气;这会将项目添加到操作栏(如果存在)。
getMenuInflater().充气(R.menu.main,menu);
返回true;
}
@凌驾
受保护的void onResume(){
super.onResume();
setupmapifneed();
}
搜索上的公共无效(视图){
字符串位置=atvPlaces.getText().toString();
List addressList=null;
if(location!=null | | location.equals(“”){
Geocoder Geocoder=新的Geocoder(本);
试一试{
addressList=geocoder.getFromLocationName(位置,1);
}捕获(IOE异常){
e、 printStackTrace();
}
地址=地址列表。获取(0);
LatLng LatLng=新LatLng(address.getLatitude(),address.getLongitude());
mMap.addMarker(新的MarkerOptions().position(latLng).title(“Marker”);
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
}
}
公共void changeType(视图){
if(mMap.getMapType()==GoogleMap.MAP\u TYPE\u NORMAL){
mMap.setMapType(GoogleMap.MAP_TYPE_卫星);
}
其他的
public class CustomAutoCompleteTextView extends AutoCompleteTextView {

public CustomAutoCompleteTextView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

/** Returns the place description corresponding to the selected item */
@Override
protected CharSequence convertSelectionToString(Object selectedItem) {
    /** Each item in the autocompetetextview suggestion list is a hashmap object */
    HashMap<String, String> hm = (HashMap<String, String>) selectedItem;
    return hm.get("description");
}
}
public class PlaceJSONParser {

/** 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("predictions");
    } 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 id="";
    String reference="";
    String description="";

    try {

        description = jPlace.getString("description");
        id = jPlace.getString("id");
        reference = jPlace.getString("reference");

        place.put("description", description);
        place.put("_id",id);
        place.put("reference",reference);

    } catch (JSONException e) {
        e.printStackTrace();
    }
    return place;
}
}
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical">

<LinearLayout
    android:layout_height="wrap_content"
    android:layout_width="wrap_content">

    <AutoCompleteTextView
        android:id="@+id/atv_places"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:hint="@string/str_atv_places" />

    <Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Search"
    android:id="@+id/Bsearch"
    android:layout_gravity="right"
    android:onClick="onSearch"/>

    <Button
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Map Type"
        android:id="@+id/Btype"
        android:layout_gravity="right"
        android:onClick="changeType" />
</LinearLayout>

<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">


<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="387dp"
android:layout_height="626dp" android:id="@+id/map"
tools:context="com.example.group.taxisafe.MapsActivity"
android:name="com.google.android.gms.maps.SupportMapFragment" />
</LinearLayout>

</LinearLayout>
{
 "error_message" : "This IP, site or mobile application is not authorized to use this API key. Request received from IP address XX.XX.XX.XX, with empty referer",
"predictions" : [],
"status" : "REQUEST_DENIED"
}