将 JSON 用于 Google 地图:标记未显示

Posted

技术标签:

【中文标题】将 JSON 用于 Google 地图:标记未显示【英文标题】:Using JSON for Google Maps: Markers not Showing up 【发布时间】:2018-10-26 21:09:39 【问题描述】:

我不知道我的代码有什么问题我遵循了每个教程,并且阅读并遵循了与我有相同问题的问题的每个答案,但它对我不起作用,这是我下面的代码,请给我一个答案,不要告诉我我的问题是重复的,因为我已经知道但它对我不起作用。

mapsActivity.java

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        GoogleMap.OnMarkerClickListener,
        LocationListener 

    private GoogleMap mMap;
    GoogleApiClient mGoogleApiClient;
    Location mLastLocation;
    Marker mCurrLocationMarker;
    LocationRequest mLocationRequest;

    private static final LatLng SYDNEY = new LatLng(-33.87365, 151.20689);
    private Marker mSydney;

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

        setUpMapIfNeeded();

        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) 
            checkLocationPermission();
        
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    


    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) 
        mMap = googleMap;
        mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

        //Initialize Google Play Services
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) 
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED) 
                buildGoogleApiClient();
                mMap.setMyLocationEnabled(true);
            
         else 
            buildGoogleApiClient();
            mMap.setMyLocationEnabled(true);
        
    

    protected synchronized void buildGoogleApiClient() 
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        mGoogleApiClient.connect();
    

    @Override
    public void onConnected(Bundle bundle) 

        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(1000);
        mLocationRequest.setFastestInterval(1000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) 
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        

    

    @Override
    public void onConnectionSuspended(int i) 

    

    @Override
    public void onLocationChanged(Location location) 

        mLastLocation = location;
        if (mCurrLocationMarker != null) 
            mCurrLocationMarker.remove();
        

        //Place current location marker
        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latLng);
        markerOptions.title(String.valueOf(latLng));
        markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
        mCurrLocationMarker = mMap.addMarker(markerOptions);

        //move map camera
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        mMap.animateCamera(CameraUpdateFactory.zoomTo(11));

        // Set a listener for marker click.
        mMap.setOnMarkerClickListener(this);

        //stop location updates
        if (mGoogleApiClient != null) 
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        

    

    /** Called when the user clicks a marker. */
    @Override
    public boolean onMarkerClick(final Marker marker) 
        final String addcamera = marker.getTitle();
        RequestQueue MyRequestQueue = Volley.newRequestQueue(this);

        String url = "http://example.com";
        StringRequest MyStringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() 
            @Override
            public void onResponse(String response) 
                //This code is executed if the server responds, whether or not the response contains data.
                //The String 'response' contains the server's response.
            
        , new Response.ErrorListener()  //Create an error listener to handle errors appropriately.
            @Override
            public void onErrorResponse(VolleyError error) 
                //This code is executed if there is an error.
            
        ) 
            protected Map<String, String> getParams() 
                Map<String, String> MyData = new HashMap<String, String>();
                MyData.put("latest", addcamera); //Add the data you'd like to send to the server.
                return MyData;
            
        ;

        MyRequestQueue.add(MyStringRequest);

        // Return false to indicate that we have not consumed the event and that we wish
        // for the default behavior to occur (which is for the camera to move such that the
        // marker is centered and for the marker's info window to open, if it has one).
        return false;
    

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) 

    

    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;

    public boolean checkLocationPermission() 
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) 

            // Asking user if explanation is needed
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)) 

                // Show an explanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.

                //Prompt the user once explanation has been shown
                ActivityCompat.requestPermissions(this,
                        new String[]Manifest.permission.ACCESS_FINE_LOCATION,
                        MY_PERMISSIONS_REQUEST_LOCATION);


             else 
                // No explanation needed, we can request the permission.
                ActivityCompat.requestPermissions(this,
                        new String[]Manifest.permission.ACCESS_FINE_LOCATION,
                        MY_PERMISSIONS_REQUEST_LOCATION);
            
            return false;
         else 
            return true;
        
    

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) 
        switch (requestCode) 
            case MY_PERMISSIONS_REQUEST_LOCATION: 
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) 

                    // permission was granted. Do the
                    // contacts-related task you need to do.
                    if (ContextCompat.checkSelfPermission(this,
                            Manifest.permission.ACCESS_FINE_LOCATION)
                            == PackageManager.PERMISSION_GRANTED) 

                        if (mGoogleApiClient == null) 
                            buildGoogleApiClient();
                        
                        mMap.setMyLocationEnabled(true);
                    

                 else 

                    // Permission denied, Disable the functionality that depends on this permission.
                    Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
                
                return;
            

            // other 'case' lines to check for other permissions this app might request.
            // You can add here other case statements according to your requirement.
        
    

    @Override
    protected void onResume() 
        super.onResume();
        setUpMapIfNeeded();
    

    private void setUpMapIfNeeded() 
        if (mMap == null) 
            SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
            mapFragment.getMapAsync(this);
            if (mMap != null) 
                //setUpMap();
                new MarkerTask().execute();
            
        
    

markerTask.java

class MarkerTask extends AsyncTask<Void, Void, String> 

    private static final String LOG_TAG = "ExampleApp";

    private static final String SERVICE_URL = "https://api.myjson.com/bins/4jb09";

    private GoogleMap mMap;

    // Invoked by execute() method of this object
    @Override
    protected String doInBackground(Void... args) 

        HttpURLConnection conn = null;
        final StringBuilder json = new StringBuilder();
        try 
            // Connect to the web service
            URL url = new URL(SERVICE_URL);
            conn = (HttpURLConnection) url.openConnection();
            InputStreamReader in = new InputStreamReader(conn.getInputStream());

            // Read the JSON data into the StringBuilder
            int read;
            char[] buff = new char[1024];
            while ((read = in.read(buff)) != -1) 
                json.append(buff, 0, read);
            
         catch (IOException e) 
            Log.e(LOG_TAG, "Error connecting to service", e);
            //throw new IOException("Error connecting to service", e); //uncaught
         finally 
            if (conn != null) 
                conn.disconnect();
            
        

        return json.toString();
    

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

        try 
            // De-serialize the JSON string into an array of city objects
            JSONArray jsonArray = new JSONArray(json);
            for (int i = 0; i < jsonArray.length(); i++) 
                JSONObject jsonObj = jsonArray.getJSONObject(i);

                LatLng latLng = new LatLng(jsonObj.getJSONArray("latlng").getDouble(0),
                        jsonObj.getJSONArray("latlng").getDouble(1));

                //move CameraPosition on first result
                if (i == 0) 
                    CameraPosition cameraPosition = new CameraPosition.Builder()
                            .target(latLng).zoom(13).build();

                    mMap.animateCamera(CameraUpdateFactory
                            .newCameraPosition(cameraPosition));
                

                // Create a marker for each city in the JSON data.
                mMap.addMarker(new MarkerOptions()
                        .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE))
                        .title(jsonObj.getString("name"))
                        .snippet(Integer.toString(jsonObj.getInt("population")))
                        .position(latLng));
            
         catch (JSONException e) 
            Log.e(LOG_TAG, "Error processing JSON", e);
        

    

activity_maps.xml

<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_
    android:layout_
    tools:context=".MapsActivity" />

【问题讨论】:

没有显示标记吗? 您需要将 LatLng 的新对象创建为 .position(new LatLng(Latitude, Longitude),并且正如您所说,您要添加 Markers 而不是将 .addMarker() 放入 for 循环中的标记。 @Barns 没有显示标记 在您的MarkerTask 类中,我看不到“mMap”设置为GoogleMap 对象的位置。看起来MarkerTask 位于一个单独的 java 文件中,所以它不会从您的“MapsActivity”Activity 中获得任何“mMap”@ 获取权限是一项异步任务,但即使在授予权限之前,我认为 onMapReady 已被调用,并且您的 GoogleApiClient 对象永远不会被创建。 【参考方案1】:

对于将来遇到这个问题的人,我使用了这个很棒的教程,感谢它的所有者,我添加了下面的链接,它与我的代码完全不同,但它正在做我想做的事。 https://github.com/rrsaikat/MultipleMarker_Using_Volley/blob/master/app/src/main/java/com/rrrsaikat88gmail/multiplemarker_using_volley/MapsActivity.java

我们不再需要markerTask类了,最后的代码是:

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,LocationListener,GoogleMap.OnMarkerClickListener 

    private GoogleMap mMap;
    public static final String URL="http://rrsaikat.mydiscussion.net/myjson/location.php";
    private JSONArray result;

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



        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

    

    @Override
    public void onMapReady(GoogleMap googleMap) 
        mMap = googleMap;
        googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
        
            return;
        
        mMap.setMyLocationEnabled(true);

        RequestQueue requestQueue= Volley.newRequestQueue(getApplicationContext());
        StringRequest stringRequest=new StringRequest(Request.Method.GET, URL, new Response.Listener<String>() 
            @Override
            public void onResponse(String response) 
                Log.d("JSONResult" , response.toString());
                JSONObject j = null;
                try
                    j =new JSONObject(response);
                    result = j.getJSONArray("FL");
                    for(int i=0;i<result.length();i++)
                        JSONObject jsonObject1=result.getJSONObject(i);
                        String lat_i = jsonObject1.getString("1");
                        String long_i = jsonObject1.getString("2");

                        mMap.addMarker(new MarkerOptions()
                                .position(new LatLng(Double.parseDouble(lat_i) , Double.parseDouble(long_i)))
                                .title(Double.valueOf(lat_i).toString() + "," + Double.valueOf(long_i).toString())
                                .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE))
                        );

                        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(23.6850,90.3563), 6.0f));
                    

                catch (NullPointerException e)
                    e.printStackTrace();

                

                catch (JSONException e)
                    e.printStackTrace();
                
            
        , new Response.ErrorListener() 
            @Override
            public void onErrorResponse(VolleyError error) 
                error.printStackTrace();
                Toast.makeText(MapsActivity.this, error.getMessage(), Toast.LENGTH_LONG).show();
            
        );


        int socketTimeout = 10000;
        RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
        stringRequest.setRetryPolicy(policy);
        requestQueue.add(stringRequest);

    


    @Override
    public void onLocationChanged(Location location) 

    

    @Override
    public void onStatusChanged(String s, int i, Bundle bundle) 

    

    @Override
    public void onProviderEnabled(String s) 

    

    @Override
    public void onProviderDisabled(String s) 

    

    @Override
    public boolean onMarkerClick(Marker marker) 
        return false;
    

【讨论】:

以上是关于将 JSON 用于 Google 地图:标记未显示的主要内容,如果未能解决你的问题,请参考以下文章

将 Google json 地图标记限制为可查看的地图

Google地图:恢复地图活动后未显示新标记

谷歌地图标记未在 Chrome 中显示

标记组件未显示在 React JS 中的 Google 地图上

标记未在 Android 中的地图上显示

来自 JSON 的 Google 地图上的标记