Google Maps Places API 不工作

Posted

技术标签:

【中文标题】Google Maps Places API 不工作【英文标题】:Google maps Places API not working 【发布时间】:2015-06-05 20:28:29 【问题描述】:
package com.example.googlemapstestproject;

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

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

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.GoogleMap.OnMyLocationButtonClickListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MainActivity extends ActionBarActivity implements OnMapLongClickListener, OnMyLocationButtonClickListener,
        android.view.View.OnClickListener 

    private GoogleMap mMap;
    Button userLocation;`enter code here`
    GPSTracker gps;

    PlacesTask placesTask;
    ParserTask parserTask;

    AutoCompleteTextView autoCompView;

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

        autoCompView = (AutoCompleteTextView) findViewById(R.id.atv_places);


        autoCompView.setThreshold(1);

        autoCompView.addTextChangedListener(new TextWatcher() 

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

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

            @Override
            public void afterTextChanged(Editable s) 
                // TODO Auto-generated method stub

            
        );

        try 
            // Loading map
            initilizeMap();

         catch (Exception e) 
            e.printStackTrace();
        

        mMap.setOnMapLongClickListener(this);
        mMap.setMyLocationEnabled(true);
        mMap.getUiSettings().setZoomControlsEnabled(true);
    


    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=AIzaSyDTg7d-JNRLRxe75QDEEeAGr1xnSHGX9V4";

            String input = "";

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

            // place type to be searched
            String types = "types=(cities)";

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


        // Executed after the complete execution of doInBackground() method
        @Override
        protected void onPostExecute(String result) 

            // Instantiating ParserTask which parses the json data from
            // Geocoding webservice
            // in a non-ui thread
            ParserTask parserTask = new ParserTask();

            // Start parsing the places in JSON format
            // Invokes the "doInBackground()" method of the class ParseTask
            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
                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[]  R.layout.listview_layout ;

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

            // Setting the adapter
            autoCompView.setAdapter(adapter);
        
    

    @Override
    public void onClick(View v) 
        // TODO Auto-generated method stub

    

更新的代码更新,一切看起来都很好,只是当我输入一个地方时没有任何东西出现。

我也用列表视图制作了一半的谷歌地图,所以如果有人有任何好的解决方案来让它们一起工作,那就太好了。

【问题讨论】:

哪些位不起作用?尝试创建一个MVCE,以便其他人可以更好地帮助您解决特定问题,而不是“这不起作用!”并且您可能还会发现创建 MVCE 的行为可以帮助您在需要询问之前了解问题所在。 我在屏幕上有文本视图,但是当我输入一个地方时没有任何反应 您的代码示例有 351 行长,对于一个随机的陌生人来说,在没有进一步帮助的情况下被要求为您调试太多了。尝试减少您发布的代码,直到您拥有 MVCE 并且您发现问题至少存在于单个方法或类中。 我不确定问题出在哪里,所以我希望得到一些关于它是否设置正确以及代码是否正常的输入。 从上面的代码中,您没有在ParseTaskonPostExecute() 方法中更新列表视图。您可以查看本教程以了解有关实施的一些详细信息:wptrafficanalyzer.in/blog/… 【参考方案1】:

如果您想使用提供GooglePlaceAutoComplete 小部件的库,请查看Sprockets(我是开发人员)。使用您的 API 密钥进行设置后,您可以在布局中添加一个可以工作的 Places API 自动完成功能,如下所示:

<net.sf.sprockets.widget.GooglePlaceAutoComplete
    xmlns:sprockets="http://schemas.android.com/apk/res-auto"
    android:id="@+id/place"
    android:layout_
    android:layout_
    sprockets:types="(cities)"/>

【讨论】:

感谢您的帮助,但请您提供有关如何实施以及如何工作的进一步说明。干杯

以上是关于Google Maps Places API 不工作的主要内容,如果未能解决你的问题,请参考以下文章

从 Google Maps Places API 中删除占位符文本

Google Maps Places API 不工作

google.maps.places.Autocomplete 语言输出

在 Google Maps Places API 中更改默认文本“输入位置”

Google Maps Places API - 如何获取地名? [复制]

CORS 和 Google Maps Places Autocomplete API 调用 [重复]