Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/350.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 谷歌地图:恢复地图活动后不会显示新标记_Java_Android_Google Maps_Maps_Google Maps Markers - Fatal编程技术网

Java 谷歌地图:恢复地图活动后不会显示新标记

Java 谷歌地图:恢复地图活动后不会显示新标记,java,android,google-maps,maps,google-maps-markers,Java,Android,Google Maps,Maps,Google Maps Markers,我正在将我的应用程序连接到传感器,每次传感器发送数据时,都会在地图上放置一个标记,其中包含信息窗口内的数据 当我第一次开始活动时mMap的ID为21319。 在我的onLocationChanged()方法中,我向ID为21319的地图添加了标记。然后,如果我按下后退按钮并继续活动mMap再次创建,现在有另一个ID,比如说ID 22431。使用我的方法addMapPoints()将旧标记添加到mMap,ID为22431,带有mMap.addMarker(markerOptions),我可以在屏幕

我正在将我的应用程序连接到传感器,每次传感器发送数据时,都会在地图上放置一个标记,其中包含信息窗口内的数据

当我第一次开始活动时<代码>mMap的ID为21319。 在我的
onLocationChanged()
方法中,我向ID为21319的地图添加了标记。然后,如果我按下后退按钮并继续活动
mMap
再次创建,现在有另一个ID,比如说ID 22431。使用我的方法
addMapPoints()
将旧标记添加到
mMap
,ID为22431,带有
mMap.addMarker(markerOptions)
,我可以在屏幕上看到标记。但这一次,当发送新数据并在
onLocationChanged()中添加标记时,屏幕上不会出现新标记。当我调试时,我可以看到在
onLocationChanged()
my
mMap
中有旧ID:21319,我没有收到任何错误。所以我猜新的标记会添加到旧地图中,但我的屏幕会显示新地图

为什么会这样?我怎样才能解决这个问题呢

更新我想我已经发现了问题。当发送新数据时,
mMap==null
。我现在想知道的是,如何在
OnLocationUpdate()
OnResume()中获取映射

这是我的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();
    }
公共类MapsActivity扩展了FragmentActivity在MapreadyCallback、GoogleAppClient.ConnectionCallbacks、GoogleAppClient.OnConnectionFailedListener、LocationListener上的实现
{
公共谷歌地图;
GoogleapClient MGoogleapClient;
位置mLastLocation;
标记器mCurrLocationMarker;
私人国际公司;
二号私人大厦;
位置请求mLocationRequest;
私有布尔初始化EAPP;
字符串当前时间;
TcpClient mTcpClient;
ArrayList markerArrayList;
静态ArrayList markerLat=新ArrayList();
静态ArrayList markerLng=新的ArrayList();
静态ArrayList markerSnippet=新ArrayList();
静态ArrayList markerTitle=新ArrayList();
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_映射);
if(android.os.Build.VERSION.SDK\u INT>=Build.VERSION\u CODES.M){
checkLocationPermission();
}
//获取SupportMapFragment,并在地图准备好使用时收到通知。
SupportMapFragment mapFragment=(SupportMapFragment)getSupportFragmentManager()
.findFragmentById(R.id.map);
getMapAsync(这个);
initiateApp=true;
markerArrayList=新的ArrayList();
}
@凌驾
受保护的void onResume(){
super.onResume();
}
@凌驾
受保护的void onPause(){
super.onPause();
markerArrayList.clear();
}
/**
*一旦可用,就可以操纵贴图。
*当映射准备好使用时,将触发此回调。
*这是我们可以添加标记或线条、添加侦听器或移动摄影机的地方。在这种情况下,
*我们只是在澳大利亚悉尼附近加了一个标记。
*如果设备上未安装Google Play服务,系统将提示用户安装
*它位于SupportMapFragment内。此方法仅在用户
*已安装Google Play服务并返回应用程序。
*/
@凌驾
4月1日公开作废(谷歌地图谷歌地图){
mMap=谷歌地图;
mMap.setMapType(GoogleMap.MAP\u TYPE\u HYBRID);
mMap.setMyLocationEnabled(真);
//初始化Google Play服务
if(android.os.Build.VERSION.SDK\u INT>=Build.VERSION\u CODES.M){
如果(ContextCompat.checkSelfPermission)(此,
清单.权限.访问(位置)
==PackageManager.权限(已授予){
buildGoogleAppClient();
}
}
否则{
buildGoogleAppClient();
}
if(markerLat!=null){
addMapPoints();
}
}
/*这里我们创建了infoWindow**/
受保护的同步无效BuildGoogleAppClient(){
mgoogleapclient=新的Googleapclient.Builder(此)
.addConnectionCallbacks(此)
.addOnConnectionFailedListener(此)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
@凌驾
未连接的公共空间(捆绑包){
getNewLocation();
新建ConnectTask()。执行(“”);
}
public void newData(JSONObject d){
试一试{
co_mV=d.getInt(“co_mV”);
no2_mV=d.getInt(“no2_mV”);
}捕获(JSONException e){
e、 printStackTrace();
}
getNewLocation();
}
public-void-getTime(){
Calendar cal=Calendar.getInstance();
currentTime=新的SimpleDataFormat(“HH:mm:ss”).format(cal.getTime());
}
public void getNewLocation(){
mlLocationRequest=新位置请求();
mLocationRequest.setPriority(位置请求.优先级高精度);
如果(ContextCompat.checkSelfPermission)(此,
清单.权限.访问(位置)
==PackageManager.权限(已授予){
LocationServices.FusedLocationApi.RequestLocationUpdate(mgoogleapClient、mlLocationRequest、this);
}
}
public void addMapPoints(){
markerArrayList=新的ArrayList();
对于(int i=0;i1){
if(位置距离到(mLastLocation)<30){
获取(markerArrayList.size()-1.remove();
@Override
public void onDestroy() {

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


}