2017-04-19 2 views
0

센서에 앱을 연결하고 있습니다. 센서가 데이터를 전송할 때마다 정보창 내부의 데이터가있는지도에 마커가 배치됩니다.Google지도 :지도 작업을 다시 시작한 후 새 마커가 표시되지 않습니다.

처음 활동을 시작할 때. mMap은 ID : 21319입니다. 내 onLocationChanged() 메서드에서 ID 21319 인지도에 표식을 추가합니다. 그런 다음 뒤로 버튼을 누르고 활동을 재개하면됩니다. mMap이 다시 만들어졌으며 이제 ID가 22431이됩니다. 내 방법이 addMapPoints() 인 경우 mMap에 ID 22431 인 이전 마커를 추가하고 mMap.addMarker(markerOptions)으로 마커를 볼 수 있습니다. 그러나 이번에는 새로운 데이터가 전송되고 마커가 내부에 추가됩니다. onLocationChanged() 새 마커가 화면에 표시되지 않습니다. 내가 디버그 할 때 나는 onLocationChanged()에 내 mMap이 이전 ID : 21319를 가지고 있으며 오류가 발생하지 않음을 알 수 있습니다. 그래서 새로운 마커가 이전 맵에 추가되었지만 내 화면에는 새 맵이 표시됩니다.

왜 이런 일이 발생합니까? 어떻게이 문제를 해결할 수 있습니까?

업데이트 나는이 문제를 발견했다고 생각합니다. 새로운 데이터가 전송되는 순간 mMap == null. 지금 궁금한 점은 OnLocationUpdate() 또는 OnResume() 안에있는지도를 어떻게 얻을 수 있습니까?

는 여기에 내가들의 OnDestroy 방법의 응용 프로그램을 종료하여이 문제를 해결 내 MapsActivity 코드

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

public GoogleMap mMap; 
GoogleApiClient mGoogleApiClient; 
Location mLastLocation; 
Marker mCurrLocationMarker; 
private int co_mV; 
private int no2_mV; 
LocationRequest mLocationRequest; 
private boolean initiateApp; 
String currentTime; 

TcpClient mTcpClient; 
ArrayList<Marker> markerArrayList; 
static ArrayList<Double> markerLat = new ArrayList<>(); 
static ArrayList<Double> markerLng = new ArrayList<>(); 
static ArrayList<String> markerSnippet = new ArrayList<>(); 
static ArrayList<String> markerTitle = new ArrayList<>(); 




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

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

    initiateApp = true; 
    markerArrayList = new ArrayList<>(); 

} 

@Override 
protected void onResume() { 
    super.onResume(); 
} 

@Override 
protected void onPause() { 
    super.onPause(); 
    markerArrayList.clear(); 
} 

/** 
* 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_HYBRID); 
    mMap.setMyLocationEnabled(true); 



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

     } 
    } 
    else { 
      buildGoogleApiClient(); 
     } 

    if (markerLat != null) { 
     addMapPoints(); 
    } 

    } 


/* Here we create the infoWindow **/ 
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) { 

    getNewLocation(); 
    new ConnectTask().execute(""); 

} 


public void newData(JSONObject d) { 
    try { 
     co_mV = d.getInt("co_mV"); 
     no2_mV = d.getInt("no2_mV"); 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 

    getNewLocation(); 
} 

public void getTime() { 

    Calendar cal = Calendar.getInstance(); 
    currentTime = new SimpleDateFormat("HH:mm:ss").format(cal.getTime()); 

} 

public void getNewLocation() { 
    mLocationRequest = new LocationRequest(); 
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 
    if (ContextCompat.checkSelfPermission(this, 
      Manifest.permission.ACCESS_FINE_LOCATION) 
      == PackageManager.PERMISSION_GRANTED) { 
     LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); 
    } 

} 

public void addMapPoints() { 
    markerArrayList = new ArrayList<>(); 
    for (int i = 0; i < markerLat.size(); i++) { 
     LatLng latLng = new LatLng(markerLat.get(i), markerLng.get(i)); 
     MarkerOptions markerOptions = new MarkerOptions(); 
     markerOptions.position(latLng); 
     markerOptions.title(markerTitle.get(i)); 
     markerOptions.snippet(markerSnippet.get(i)); 
     markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA)); 
     Marker marker = mMap.addMarker(markerOptions); 
     markerArrayList.add(marker); 
    } 
} 

@Override 
public void onConnectionSuspended(int i) { 

} 

@Override 
public void onLocationChanged(Location location) { 

    if (markerArrayList.size()>1) { 
     if(location.distanceTo(mLastLocation) < 30) { 
      markerArrayList.get(markerArrayList.size()-1).remove(); 
      markerArrayList.remove(markerArrayList.size()-1); 
      markerSnippet.remove(markerSnippet.size()-1); 
      markerTitle.remove(markerTitle.size()-1); 
      markerLat.remove(markerTitle.size()-1); 
      markerLng.remove(markerTitle.size()-1); 
      Toast.makeText(
        getApplicationContext(), 
        "Reading to close to last reading, replaces last reading", Toast.LENGTH_SHORT).show(); 
     } 
    } 


    if (markerArrayList.size() == 8) { 
     markerArrayList.get(0).remove(); 
     markerArrayList.remove(0); 
     markerSnippet.remove(0); 
     markerTitle.remove(0); 
     markerLat.remove(0); 
     markerLng.remove(0); 
    } 

    //Place current location marker 
    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude()); 

if (co_mV != 0) { 
MarkerOptions markerOptions = new MarkerOptions(); 
markerOptions.position(latLng); 
markerLat.add(location.getLatitude()); 
markerLng.add(location.getLongitude()); 
markerOptions.title("Time of reading: " + currentTime); 
markerTitle.add("Time of reading: " + currentTime); 
markerOptions.snippet("co: " + String.valueOf(co_mV) + " mV, " + "no2: " + String.valueOf(no2_mV) + " mV"); 
markerSnippet.add("co: " + String.valueOf(co_mV) + " mV, " + "no2: " + String.valueOf(no2_mV) + " mV"); 
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA)); 
mCurrLocationMarker = mMap.addMarker(markerOptions); 
markerArrayList.add(mCurrLocationMarker); 
} 



    mLastLocation = location; 


    Log.d("ADebugTag", "Value: " + Double.toString(location.getLatitude())); 
    Log.d("ADebugTag", "Value: " + Double.toString(location.getLongitude())); 


    //move map camera 

    if(initiateApp){ 
     mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15)); 
    } 

    boolean contains = mMap.getProjection() 
      .getVisibleRegion() 
      .latLngBounds 
      .contains(latLng); 

    if(!contains){ 
     mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); 
    } 

    initiateApp = 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. 
    } 
} 

public JSONObject getNewJSON(JSONObject json) { 
    try { 

     int humidity = json.getInt("humidity_ppm"); 
     int pressure = json.getInt("pressure_Pa"); 
     int noise = json.getInt("noise_dB"); 
     double lat = mLastLocation.getLatitude(); 
     double lng = mLastLocation.getLongitude(); 
     long time = System.currentTimeMillis()/1000L; 

     JSONObject c = new JSONObject(); 
     c.put("time",time); 
     c.put("lat",lat); 
     c.put("long",lng); 
     c.put("humidity",humidity); 
     c.put("pressure",pressure); 
     c.put("noise_dB",noise); 
     return c; 

    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 
+0

당신은 그것이'경우 (co_mV! = 0)'케이스에 점점 확실하다? 로깅을 추가하여 –

+0

예, (co_mV! = 0)으로 들어갑니다. 스 니펫, 제목 및 위치 모두가 새 마커에 추가됩니다. 나는 또한 mMap.addMarker (mCurrLocationMarker)에 오류를 얻지 못하고있다. 내가 볼 수있는 유일한 점은 mMap이 "addMapPoints()"내부의 mMap ID와 다른 ID를 가지고 있다는 것입니다. – Kspr

+0

'addMapPoints()'를 호출하는 유일한 곳은'onMapReady()'오버라이드에있는 것처럼 보입니다. 네가 이력서를받을 때 전화가 걸려있는거야? –

답변

0

입니다. 나는 조각이 마커를 재사용 할 때 생각 지도에 배치 할 수 없습니다

@Override 
public void onDestroy() { 

    getActivity().finish(); 
    System.exit(0); 
    super.onDestroy(); 


}