【问题标题】:MapActivity query for nearest hospital/restaurant not working最近的医院/餐厅的 MapActivity 查询不工作
【发布时间】:2016-03-02 12:02:45
【问题描述】:

编辑:已解决!除了丹尼尔的回答(救了我的命),这就是我所做的:
1. 将“MapActivity2”类替换为服务器 API 密钥。
2.让清单中的其他键和'maps_activites.xml。成为 android API 密钥
3. 在 Google Developer APIS 上启用以下 APIS:
谷歌地图 Android API
适用于 Android 的 Google Places API
Google Places API 网络服务

4. 轰隆隆!有效。无论如何,这是我的 github 存储库的代码: https://github.com/bholagabbar/AurumHealthApp
我正在尝试从我当前的位置检索最近的餐馆。我正在使用我在网上找到的代码here。但是我收到以下错误。我已经放置了整个 logcat 以供执行,并以粗体突出显示错误:

11-30 04:53:31.000 25292-25292/?我/艺术:延迟启用 -Xcheck:jni

11-30 04:53:31.033 25292-25302/? I/art:调试器不再处于活动状态
11-30 04:53:31.100 25292-25311/? I/GMPM:应用程序测量正在启动
11-30 04:53:31.109 25292-25311/? E/GMPM:getGoogleAppId 失败,状态为:10
11-30 04:53:31.111 25292-25311/? E/GMPM:无法上传。应用衡量功能已停用

11-30 04:53:31.125 25292-25314/? D/OpenGLRenderer: 使用 EGL_SWAP_BEHAVIOR_PRESERVED: true`11-30 04:53:31.135 25292-25292/? D/Atlas:正在验证地图...
11-30 04:53:31.178 25292-25314/? I/Adreno-EGL: : EGL 1.4 高通构建: (Ibddc658e36)
11-30 04:53:31.178 25292-25314/? I/Adreno-EGL:OpenGL ES 着色器编译器版本:E031.25.03.04
11-30 04:53:31.178 25292-25314/? I/Adreno-EGL:构建日期:08/10/15 Mon
11-30 04:53:31.178 25292-25314/? I/Adreno-EGL:本地分支:工作区
11-30 04:53:31.178 25292-25314/? I/Adreno-EGL:远程分支:
11-30 04:53:31.178 25292-25314/? I/Adreno-EGL:本地补丁:
11-30 04:53:31.178 25292-25314/? I/Adreno-EGL:重建分支:
11-30 04:53:31.179 25292-25314/? I/OpenGLRenderer:初始化 EGL,版本 1.4
11-30 04:53:31.193 25292-25314/? D/OpenGLRenderer:启用调试模式 0
11-30 04:53:32.663 25292-25292/com.iotaconcepts.aurum I/Choreographer:跳过 37 帧!应用程序可能在其主线程上做太多工作。
11-30 04:53:32.737 25292-25314/com.iotaconcepts.aurum V/RenderScript:应用程序请求 CPU 执行
11-30 04:53 :32.747 25292-25314/com.iotaconcepts.aurum V/RenderScript: 0xb7f96960 启动线程,CPU 4
11-30 04:53:36.092 25292-25292/com.iotaconcepts.aurum D/AndroidRuntime: 关闭虚拟机
11-30 04:53:36.093 25292-25292/com.iotaconcepts.aurum E/AndroidRuntime:致命异常:主要
11-30 04:53:36.093 25292-25292/com.iotaconcepts.aurum E /AndroidRuntime: 进程: com.iotaconcepts.aurum, PID: 25292
11-30 04:53:36.093 25292-25292/com.iotaconcepts.aurum E/AndroidRuntime: java.lang.RuntimeException: 无法启动活动 ComponentInfo{ com.iotaconcepts.aurum/com.iotaconcepts.aurum.MapsActivity2}:java.lang.NullPointerException:尝试调用虚拟方法'void com.google.android.gms.maps.SupportMapFragment.getMapAsync(com.google.android.gms。 maps.OnMapReadyCallback)' 在空对象引用上e
11-30 04:53:36.093 25292-25292/com.iotaconcepts.aurum E/AndroidRuntime:在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2339)
11-30 04:53: 36.093 25292-25292/com.iotaconcepts.aurum E/AndroidRuntime:在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2413)
11-30 04:53:36.093 25292-25292/com.iotaconcepts.aurum E /AndroidRuntime: 在 android.app.ActivityThread.access$800(ActivityThread.java:155)
11-30 04:53:36.093 25292-25292/com.iotaconcepts.aurum E/AndroidRuntime: 在 android.app.ActivityThread$ H.handleMessage(ActivityThread.java:1317)
11-30 04:53:36.093 25292-25292/com.iotaconcepts.aurum E/AndroidRuntime: 在 android.os.Handler.dispatchMessage(Handler.java:102)11-30 04:53:36.093 25292-25292/com.iotaconcepts.aurum E/AndroidRuntime: 在 android.os.Looper.loop(Looper.java:135)
11-30 04:53:36.093 25292 -25292/com.iotaconcepts.aurum E/AndroidRuntime:在 android.app.ActivityThread.main(ActivityThread.jav a:5343)
11-30 04:53:36.093 25292-25292/com.iotaconcepts.aurum E/AndroidRuntime:在 java.lang.reflect.Method.invoke(本机方法)
11-30 04: 53:36.093 25292-25292/com.iotaconcepts.aurum E/AndroidRuntime: 在 java.lang.reflect.Method.invoke(Method.java:372)
11-30 04:53:36.093 25292-25292/com. iotaconcepts.aurum E/AndroidRuntime:在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:907)
11-30 04:53:36.093 25292-25292/com.iotaconcepts.aurum E/ AndroidRuntime:在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:702)
11-30 04:53:36.093 25292-25292/com.iotaconcepts.aurum E/AndroidRuntime: 由: java.lang.NullPointerException: 尝试在空对象引用上调用虚拟方法“void com.google.android.gms.maps.SupportMapFragment.getMapAsync(com.google.android.gms.maps.OnMapReadyCallback)”
11 -30 04:53:36.093 25292-25292/com.iotaconcepts.aurum E/AndroidRuntime:在 com.iotaconcepts.aurum.MapsActivity2.onCreate(地图sActivity2.java:42)

11-30 04:53:36.093 25292-25292/com.iotaconcepts.aurum E/AndroidRuntime: 在 android.app.Activity.performCreate(Activity.java:6010)11-30 04:53:36.093 25292-25292/com.iotaconcepts.aurum E/AndroidRuntime: 在 android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1129)
11-30 04:53:36.093 25292 -25292/com.iotaconcepts.aurum E/AndroidRuntime:在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2292)
11-30 04:53:36.093 25292-25292/com.iotaconcepts.aurum E/AndroidRuntime : 在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2413)
11-30 04:53:36.093 25292-25292/com.iotaconcepts.aurum E/AndroidRuntime: 在 android.app.ActivityThread.access$800( ActivityThread.java:155)
11-30 04:53:36.093 25292-25292/com.iotaconcepts.aurum E/AndroidRuntime: 在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1317)
11-30 04:53:36.093 25292-25292/com.iotaconcepts.aurum E/AndroidRun时间:在 android.os.Handler.dispatchMessage(Handler.java:102)
11-30 04:53:36.093 25292-25292/com.iotaconcepts.aurum E/AndroidRuntime: 在 android.os.Looper.loop( Looper.java:135)
11-30 04:53:36.093 25292-25292/com.iotaconcepts.aurum E/AndroidRuntime: 在 android.app.ActivityThread.main(ActivityThread.java:5343)
11- 30 04:53:36.093 25292-25292/com.iotaconcepts.aurum E/AndroidRuntime: 在 java.lang.reflect.Method.invoke(Native Method)
11-30 04:53:36.093 25292-25292/com. iotaconcepts.aurum E/AndroidRuntime:在 java.lang.reflect.Method.invoke(Method.java:372)
11-30 04:53:36.093 25292-25292/com.iotaconcepts.aurum E/AndroidRuntime:在 com .android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:907)
11-30 04:53:36.093 25292-25292/com.iotaconcepts.aurum E/AndroidRuntime:在 com.android.internal。 os.ZygoteInit.main(ZygoteInit.java:702)

在过去的 2 个小时里,我一直在想办法找出我们的错误,但徒劳无功。这是活动的代码:

编辑修复后,这里是代码

包 com.iotaconcepts.aurum;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

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 MapsActivity2 extends AppCompatActivity implements OnMapReadyCallback
{
    private GoogleMap mGoogleMap;
    SupportMapFragment mapFrag;

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

        mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFrag.getMapAsync(this);

    }

    @Override
    public void onMapReady(GoogleMap googleMap)
    {
        mGoogleMap=googleMap;
        mGoogleMap.setMyLocationEnabled(true);
        StringBuilder sbValue = new StringBuilder(sbMethod());
        PlacesTask placesTask = new PlacesTask();
        placesTask.execute(sbValue.toString());
    }

    public StringBuilder sbMethod()
    {

        //use your current location here
        double mLatitude = 37.77657;
        double mLongitude = -122.417506;

        StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
        sb.append("location=" + mLatitude + "," + mLongitude);
        sb.append("&radius=5000");
        sb.append("&types=" + "restaurant");
        sb.append("&sensor=true");

        sb.append("&key=AIza************************");

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

}

XML 文件是:

        <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical" android:layout_width="match_parent"
              android:layout_height="match_parent">

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:tools="http://schemas.android.com/tools"
              xmlns:map="http://schemas.android.com/apk/res-auto"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:id="@+id/map"
              tools:context="com.iotaconcepts.aurum.MapsActivity2"
              android:name="com.google.android.gms.maps.SupportMapFragment"/>

</LinearLayout>

清单文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.iotaconcepts.aurum" >

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <uses-library android:name="com.google.android.maps" />

    <!-- uses-permission android:name="android.permission.INTERNET" / -->
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/MyMaterialTheme" >
        <activity
            android:name=".MainActivity"
            android:label="Aurum" >
            <intent-filter>
                <action android:name="android.intent.action.MAINACTIVITY" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        <activity
            android:name=".LoginActivity"
            android:label="Aurum"
            android:theme="@style/ColorfulActionBarTheme" >
            <intent-filter>
                <action android:name="android.intent.action.LOGIN" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Splash"
            android:label="Aurum"
            android:theme="@style/ColorfulActionBarTheme" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Diagnosis"
            android:label="Aurum"
            android:theme="@style/Theme.Transparent" >
            <intent-filter>
                <action android:name="android.intent.action.DIAGNOSIS" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>

        <!--
             The API key for Google Maps-based APIs is defined as a string resource.
             (See the file "res/values/google_maps_api.xml").
             Note that the API key is linked to the encryption key used to sign the APK.
             You need a different API key for each encryption key, including the release key that is used to
             sign the APK for publishing.
             You can define the keys for the debug and release targets in src/debug/ and src/release/. 
        -->
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="AIza*************************" />

        <activity
            android:name=".MapsActivity2"
            android:label="@string/title_activity_maps2" >
        </activity>
        <activity android:name=".testactivity" >
        </activity>
    </application>

</manifest>

【问题讨论】:

  • 我也有一些错误。你能修好吗?
  • 您是否使用服务器 api 密钥进行附近地点查询?
  • 在'把你的钥匙放在这里'我已经把它放好了。它也被自动放置在清单文件中

标签: android android-activity google-maps-android-api-2


【解决方案1】:

我刚刚运行了您的代码并使其正常工作。看起来主要问题是key 和查询 url 中的 api 键之间有一个空格。

您也没有任何调用 getMapAsync() 的代码,因此您没有获得地图参考,也不会调用 onMapReady()

此外,请务必将服务器 API 密钥与 Places Web API 一起使用。

这是对我有用的代码:

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
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 MapsActivity2 extends AppCompatActivity implements OnMapReadyCallback
{
    private GoogleMap mGoogleMap;
    SupportMapFragment mapFrag;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        //Wrong one:
        //setContentView(R.layout.activity_main);

        //Use this one:
        setContentView(R.layout.activity_maps2);

        mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFrag.getMapAsync(this);

    }

    @Override
    public void onMapReady(GoogleMap googleMap)
    {
        mGoogleMap=googleMap;
        mGoogleMap.setMyLocationEnabled(true);
        StringBuilder sbValue = new StringBuilder(sbMethod());
        PlacesTask placesTask = new PlacesTask();
        placesTask.execute(sbValue.toString());
    }

    public StringBuilder sbMethod()
    {

        //use your current location here
        double mLatitude = 37.77657;
        double mLongitude = -122.417506;

        StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
        sb.append("location=" + mLatitude + "," + mLongitude);
        sb.append("&radius=5000");
        sb.append("&types=" + "restaurant");
        sb.append("&sensor=true");

        sb.append("&key=AIza******************************");

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

}

activity_maps2.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:map="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/map"
        tools:context="com.iotaconcepts.aurum.MapsActivity2"
        android:name="com.google.android.gms.maps.SupportMapFragment"/>

</LinearLayout>

结果:

【讨论】:

  • 我收到以下错误:原因:java.lang.NullPointerException:尝试调用虚拟方法'void com.google.android.gms.maps.SupportMapFragment.getMapAsync(com.google.android. gms.maps.OnMapReadyCallback)' 在空对象引用 11-30 04:22:19.877 18700-18700/com.iotaconcepts.aurum E/AndroidRuntime: at com.iotaconcepts.aurum.MapsActivity.onCreate(MapsActivity.java:42)
  • @bholagabbar 你确定你使用的是相同的布局xml吗?它应该可以毫无问题地找到R.id.map。不知道为什么它对你来说是空的。
  • 既然您提到了它,我遇到了渲染问题。它说“无法检测片段”。让我尝试从上面提到的答案中复制粘贴相同的 XML 代码。
  • 当然,我基本上使用了你的,但是包裹在一个 LinearLayout 中。
  • 你去。问题已更新。应该给你一个更好的主意
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-09
  • 1970-01-01
  • 2016-07-14
  • 2023-04-07
  • 2014-10-09
相关资源
最近更新 更多