地图活动中的多个标记

时间:2016-12-18 09:28:08

标签: android google-maps

我想在我的地图中显示多个位置,并在标记中写下他们的名字......我已经尝试了几天,但我似乎无法理解这一点 这是我的代码

公共类MapsActivity扩展了FragmentActivity {

private GoogleMap googleMap;
private ArrayList<LatLng> listLatLng;
private RelativeLayout rlMapLayout;
HashMap<Marker, LatLngBean> hashMapMarker = new HashMap<Marker, LatLngBean>();

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

    rlMapLayout = (RelativeLayout) findViewById(R.id.rlMapLayout);

    setUpMapIfNeeded();
    setData();

}

private void setData() {
    ArrayList<LatLngBean> arrayList = new ArrayList<LatLngBean>();
    LatLngBean bean = new LatLngBean();
    bean.setTitle("Ahmedabad");
    bean.setSnippet("Hello,Ahmedabad");
    bean.setLatitude("23.0300");
    bean.setLongitude("72.5800");
    arrayList.add(bean);

    LatLngBean bean1 = new LatLngBean();
    bean1.setTitle("Surat");
    bean1.setSnippet("Hello,Surat");
    bean1.setLatitude("21.1700");
    bean1.setLongitude("72.8300");
    arrayList.add(bean1);

    LatLngBean bean2 = new LatLngBean();
    bean2.setTitle("Vadodara");
    bean2.setSnippet("Hello,Vadodara");
    bean2.setLatitude("22.3000");
    bean2.setLongitude("73.2000");
    arrayList.add(bean2);

    LoadingGoogleMap(arrayList);
}

/**
 * @author Hasmukh Bhadani
 * Set googleMap if require
 */
private void setUpMapIfNeeded() {
    int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());

    // Google Play Services are not available
    if (status != ConnectionResult.SUCCESS) {
        int requestCode = 10;
        Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
        dialog.show();

    } else {
        if (googleMap == null) {
            googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
            if (googleMap != null) {
                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) {
                    // TODO: Consider calling
                    //    ActivityCompat#requestPermissions
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for ActivityCompat#requestPermissions for more details.
                    return;
                }
                googleMap.setMyLocationEnabled(true);
                googleMap.getUiSettings().setMyLocationButtonEnabled(true);
                googleMap.getUiSettings().setZoomControlsEnabled(true);
            }
        }
    }
}

/**
 * @author Hasmukh Bhadani
 * Loading Data to the GoogleMap
 */
// -------------------------Google Map
void LoadingGoogleMap(ArrayList<LatLngBean> arrayList) {
    if (googleMap != null) {
        googleMap.clear();
        googleMap.getUiSettings().setMyLocationButtonEnabled(true);
        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) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        googleMap.setMyLocationEnabled(true);
        googleMap.getUiSettings().setZoomControlsEnabled(true);

        if(arrayList.size()>0)
        {
            try
            {
                listLatLng=new ArrayList<LatLng>();
                for (int i = 0; i < arrayList.size(); i++)
                {
                    LatLngBean bean=arrayList.get(i);
                    if(bean.getLatitude().length()>0 && bean.getLongitude().length()>0)
                    {
                        double lat=Double.parseDouble(bean.getLatitude());
                        double lon=Double.parseDouble(bean.getLongitude());

                        Marker marker = googleMap.addMarker(new MarkerOptions()
                                .position(new LatLng(lat,lon))
                                .title(bean.getTitle())
                                .snippet(bean.getSnippet())
                                .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));

                        //Add Marker to Hashmap
                        hashMapMarker.put(marker,bean);

                        //Set Zoom Level of Map pin
                        LatLng object=new LatLng(lat, lon);
                        listLatLng.add(object);
                    }
                }
                SetZoomlevel(listLatLng);
            }
            catch (NumberFormatException e)
            {
                e.printStackTrace();
            }

            googleMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {

                @Override
                public void onInfoWindowClick(Marker position)
                {
                    LatLngBean bean=hashMapMarker.get(position);
                    Toast.makeText(getApplicationContext(), bean.getTitle(),Toast.LENGTH_SHORT).show();

                }
            });
        }
    }

    else
    {
        Toast.makeText(getApplicationContext(),"Sorry! unable to create maps", Toast.LENGTH_SHORT).show();
    }
}
/**
 * @author Hasmukh Bhadani
 * Set Zoom level all pin withing screen on GoogleMap
 */
public void  SetZoomlevel(ArrayList<LatLng> listLatLng)
{
    if (listLatLng != null && listLatLng.size() == 1)
    {
        googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(listLatLng.get(0), 10));
    }
    else if (listLatLng != null && listLatLng.size() > 1)
    {
        final Builder builder = LatLngBounds.builder();
        for (int i = 0; i < listLatLng.size(); i++)
        {
            builder.include(listLatLng.get(i));
        }

        final ViewTreeObserver treeObserver = rlMapLayout.getViewTreeObserver();
        treeObserver.addOnGlobalLayoutListener(new OnGlobalLayoutListener()
        {
            @SuppressWarnings("deprecation")
            @Override
            public void onGlobalLayout()
            {
                if(googleMap != null){
                    googleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), findViewById(R.id.map)
                            .getWidth(), findViewById(R.id.map).getHeight(), 80));
                    rlMapLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                }
            }
        });

    }
}

}

1 个答案:

答案 0 :(得分:0)

我认为问题出在你的许可检查中

更改您的代码:从此

 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) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return;
            }

到此:

你的onCreate()

中的

 ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 1);

然后添加以下代码

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

            } else {
                // permission denied, boo! Disable the
                // functionality that depends on this permission.
                finish();
            }
            return;
        }
        // other 'case' lines to check for other
        // permissions this app might request
    }
}