2016-10-11 4 views
0

Я хотел, чтобы карта google в этом мероприятии обновлялась после нажатия кнопки alertdialog (электронные письма). Место было установлено вручную, но оно не обновляется. Он просто остается в alertdialog, и карта google просто обновляется, но не переходит в координату местоположения и возвращается как 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[]{"[email protected]", "[email protected]"}; 
       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 "[email protected]": 
          latitude = 3.22094; 
          longitude = 101.724866; 
           LatLng latLng1 = new LatLng(3.1466,101.6958); 
           mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng1)); 
           moveMap(); 
           break; 
          case "[email protected]": 
          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. 
       } 
      } 
     } 
    } 

ответ

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(); 

, поэтому он, вероятно, перемещает камеру и возвращается в предыдущее положение.

+0

Хорошо, теперь добавлен alertdialog, но карта по-прежнему не перемещается в указанное место. как вы понимаете, не устанавливая переменные широты и долготы? –

+0

Функция 'moveMap' использует переменные' широты' и 'longitude' для перемещения камеры (снова), однако перед ее вызовом вы не устанавливаете значения этих переменных в инструкции switch. –

+0

Спасибо! Он работает сейчас, но когда я нажимаю на первое письмо, он переходит ко второй координате электронной почты. –