无法在Google地图中添加多个标记

时间:2020-03-24 11:20:36

标签: android google-maps

我正在尝试通过以下代码在来自我的Google Map API上服务器的多个位置上添加多个标记

public class MapNearByCinemasActivity extends FragmentActivity implements OnMapReadyCallback {
    SupportMapFragment mapFragment;
    private static final int MY_PERMISSIONS_REQUEST_OPEN_LOCATION = 100;
    Location currentLocation;
    ArrayList<Hall> halls = new ArrayList<>();
    private MarkerOptions options = new MarkerOptions();
    FusedLocationProviderClient fusedLocationProviderClient;
    private GoogleMap mMap;
    Double lat, lon;
    ImageView satalitveIv, defaultIv;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map_nearby_cinemas);
        fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
        loadDirection();
        checkPermssion();
    }

    private void loadDirection() {
        final ProgressDialog dialog = new ProgressDialog(MapNearByCinemasActivity.this);
        dialog.show();
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, API.getlatLon, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                dialog.dismiss();
                try {
                    JSONArray dataObject = response.getJSONArray(SharedPref.key_data_details);
                    for (int i = 0; i<dataObject.length();i++){
                        JSONObject object = dataObject.getJSONObject(i);
                        Hall hall = new Gson().fromJson(object.toString(),Hall.class);
                        halls.add(hall);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                dialog.dismiss();

            }
        });
        if (CheckConnectivity.isNetworkAvailable(MapNearByCinemasActivity.this)) {
            dialog.dismiss();
            RestClient.getInstance(MapNearByCinemasActivity.this).addToRequestQueue(jsonObjectRequest);
        } else {
            dialog.dismiss();
            Toast.makeText(this, "Please Connect to the internet", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        satalitveIv = findViewById(R.id.satellite_iv);
        defaultIv = findViewById(R.id.default_iv);
        satalitveIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
            }
        });
        defaultIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
            }
        });
        mMap = googleMap;
//        mMap.getMapType();
        mMap.setMyLocationEnabled(true);
//        mMap.getUiSettings().setZoomControlsEnabled(true);
//        mMap.getUiSettings().setZoomGesturesEnabled(true);
        LatLng latLng = new LatLng(lat, lon); //current location
        mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng)); //for current location of user
        mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 17));
        for(int i = 0 ; i < halls.size() ; i++) {
            Toast.makeText(this, "Method called", Toast.LENGTH_SHORT).show();
            createMarker(halls.get(i).getLat(), halls.get(i).getLon(), halls.get(i).getLocation(), halls.get(i).getName());
        }
//        Circle circle = mMap.addCircle(new CircleOptions()
//                .center(latLng)
//                .radius(50)
//                .strokeWidth(0)
//                .fillColor(Color.parseColor("#500084d3")));

    }
    protected Marker createMarker(double latitude, double longitude, String title, String snippet) {
        return mMap.addMarker(new MarkerOptions()
                .position(new LatLng(latitude, longitude))
                .anchor(0.5f, 0.5f)
                .title(title)
                .snippet(snippet)
                .icon(bitmapDescriptorFromVector(this, R.drawable.ic_marker)));
    }

    private BitmapDescriptor bitmapDescriptorFromVector(Context context, int vectorResId) {
        Drawable vectorDrawable = ContextCompat.getDrawable(context, vectorResId);
        vectorDrawable.setBounds(0, 0, vectorDrawable.getIntrinsicWidth(), vectorDrawable.getIntrinsicHeight());
        Bitmap bitmap = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(), vectorDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        vectorDrawable.draw(canvas);
        return BitmapDescriptorFactory.fromBitmap(bitmap);
    }
}

但是它仅显示我当前的位置标记。没有多个标记:(

我创建了一个loaddirection()方法来从服务器加载方向,并且它正在从服务器加载纬度。但是当我在多方向数组上添加标记时,它不会在地图上显示标记。我创建的for循环也没有执行。我在某个地方搞砸了。我尝试了这个网站上的所有内容,但没有一个帮助我。有帮助吗?

1 个答案:

答案 0 :(得分:0)

使用my created for loop is not executing too的原因是因为loadDirection()的结果尚未到达。

要解决此问题,请将my created for loop移到onReponse()内部。

@Override
public void onResponse(JSONObject response) {
      ...
      ...
      halls.add(hall);
    }

    //fixme
    for(int i = 0 ; i < halls.size() ; i++) {
      Toast.makeText(this, "Method called", Toast.LENGTH_SHORT).show();
      createMarker(halls.get(i).getLat(), halls.get(i).getLon(), halls.get(i).getLocation(), halls.get(i).getName());
    }

  } catch (JSONException e) {
  ...
  ...