【问题标题】:Map doesn't update location地图不更新位置
【发布时间】:2016-10-11 14:30:47
【问题描述】:

我想在按下警报对话框选项(电子邮件)后更新此活动中的谷歌地图。该位置已手动设置,但未更新。它只是停留在警报对话框中,谷歌地图只是刷新但不去位置坐标,它返回为 0,0。

    public class MapsTrack extends FragmentActivity implements OnMapReadyCallback,
            GoogleApiClient.ConnectionCallbacks,
            GoogleApiClient.OnConnectionFailedListener,
            GoogleMap.OnMarkerDragListener,
            GoogleMap.OnMapLongClickListener,
            LocationListener,
            View.OnClickListener {

        //Our Map
        private GoogleMap mMap;


        //To store longitude and latitude from map
        private double longitude;
        private double latitude;

        //Buttons
        private ImageButton buttonSearch;
        private ImageButton buttonCurrent;

        private static final int MY_LOCATION_REQUEST_CODE = 1;

        //Google ApiClient
        private GoogleApiClient googleApiClient;
        Location location;


        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_maps_track);
            // 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);

            //Initializing googleapi client
            googleApiClient = new GoogleApiClient.Builder(this)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API)
                    .build();

            //Initializing views and adding onclick listeners
            buttonSearch = (ImageButton) findViewById(R.id.buttonSearch);
            buttonCurrent = (ImageButton) findViewById(R.id.buttonCurrent);
            buttonSearch.setOnClickListener(this);
            buttonCurrent.setOnClickListener(this);
        }

        @Override
        protected void onStart() {
            googleApiClient.connect();
            super.onStart();
        }

        @Override
        protected void onStop() {
            googleApiClient.disconnect();
            super.onStop();
        }

        //Getting current location
        private void getCurrentLocation() {
            //Creating a location object
            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;
            }
            Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
            if (location != null) {
                //Getting longitude and latitude
                longitude = location.getLongitude();
                latitude = location.getLatitude();

                //moving the map to location
                moveMap();
            }
        }

        //Function to move the map
        private void moveMap() {
            //String to display current latitude and longitude
            String msg = latitude + ", " + longitude;

            //Creating a LatLng Object to store Coordinates
            LatLng latLng = new LatLng(latitude, longitude);

            //Adding marker to map
            mMap.addMarker(new MarkerOptions()
                    .position(latLng) //setting position
                    .draggable(true) //Making the marker draggable
                    .title("Current Location")); //Adding a title


            //Moving the camera
            mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

            //Animating the camera
            mMap.animateCamera(CameraUpdateFactory.zoomTo(15));

            //Displaying current coordinates in toast
            Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
        }

        @Override
        public void onMapReady(GoogleMap googleMap) {
            mMap = googleMap;
            LatLng latLng = new LatLng(-34, 151);
            mMap.addMarker(new MarkerOptions().position(latLng).draggable(true));
            mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
            mMap.setOnMarkerDragListener(this);
            mMap.setOnMapLongClickListener(this);
            mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

        }

        @Override
        public void onConnected(Bundle bundle) {

        }


        @Override
        public void onDestroy() {
            super.onDestroy();
        }


        @Override
        public void onLocationChanged(Location location) {

        }

        @Override
        public void onConnectionSuspended(int i) {

        }

        @Override
        public void onMapLongClick(LatLng latLng) {
            //Clearing all the markers
            mMap.clear();

            //Adding a new marker to the current pressed position
            mMap.addMarker(new MarkerOptions()
                    .position(latLng)
                    .draggable(true));
        }

        @Override
        public void onMarkerDragStart(Marker marker) {

        }

        @Override
        public void onMarkerDrag(Marker marker) {

        }

        @Override
        public void onMarkerDragEnd(Marker marker) {
            //Getting the coordinates
            latitude = marker.getPosition().latitude;
            longitude = marker.getPosition().longitude;

            //Moving the map
            moveMap();
        }

        @Override
        public void onClick(View v) {
            if (v == buttonCurrent) {
                getCurrentLocation();
                moveMap();
            } else if (v == buttonSearch) {

                final String[] names = new String[]{"ijad_wiz@gmail.com", "nadiaf33@yahoo.com"};
                final String name = names[1];
                final AlertDialog.Builder alertDialog = new AlertDialog.Builder(MapsTrack.this);
AlertDialog alert = alertDialog.create();
                LayoutInflater inflater = getLayoutInflater();
                View convertView = (View) inflater.inflate(R.layout.activity_inflate, null);
                alertDialog.setView(convertView);
                alertDialog.setTitle("Track!");
                ListView lv = (ListView) convertView.findViewById(R.id.listView1);
                ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, names);
                lv.setAdapter(adapter);
                alertDialog.show();

                lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        switch (name) {
                            case "email1@gmail.com":
                            latitude = 3.22094;
                            longitude = 101.724866;
                                LatLng latLng1 = new LatLng(3.1466,101.6958);
                                mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng1));
                                moveMap();
                                break;
                            case "email2@yahoo.com":
                            latitude = 48.8584;
                            longitude = 2.2945;
                                LatLng latLng2 = new LatLng(48.8584, 2.2945);
                                mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng2));
                                moveMap();
                                break;
                    }
                }

            });
            }
        }

        @Override
        public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        }

        @Override
        public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
            if (requestCode == MY_LOCATION_REQUEST_CODE) {
                if (permissions.length == 1 &&
                        permissions[0] == android.Manifest.permission.ACCESS_FINE_LOCATION &&
                        grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    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;
                    }
                    mMap.setMyLocationEnabled(true);
                } else {
                    // Permission was denied. Display an error message.
                }
            }
        }
    }

【问题讨论】:

    标签: android google-maps geolocation location android-alertdialog


    【解决方案1】:

    您缺少获取AlertDialog(而不是AlertDialog Builder)的代码:

    AlertDialog.Builder builder = new AlertDialog.Builder(this); 
    
    AlertDialog alert = builder.create();
    
    // Then you can call on your 
    // lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    alert.cancel();
    // }
    

    此外,您没有在此块中设置纬度和经度变量:

    LatLng latLng1 = new LatLng(3.1466,101.6958);
    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng1));
    moveMap();
    

    所以它可能会移动相机并移回之前的位置。

    【讨论】:

    • 好的,现在添加了alertdialog,但是地图仍然没有移动到指定的位置。不设置纬度和经度变量是什么意思?
    • 您的 moveMap 函数使用 latitude 和 longitude 变量来移动相机(再次),但是在调用它之前,您不要在 switch 语句中设置这些变量的值.
    • 谢谢!它现在可以工作,但是当我按下第一封电子邮件时,它会转到第二封电子邮件的坐标。
    • 错误是当您执行switch (name) 时,您总是与第二封电子邮件进行比较,因为final String name = names[1]; 这一行。你应该使用switch (names[position])。
    • 更改为 (names[position]) 但错误“预期数组类型”
    猜你喜欢
    • 2017-01-02
    • 2020-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多