как обновить значок карты через обработчик - PullRequest
0 голосов
/ 03 октября 2019

Я очень начинающий программист. Я использую обработчик, чтобы получить данные о своем местонахождении из службы в моей основной деятельности, но я хотел бы обновить карту, используя код из службы.

Координаты GPS правильно отправляются через обработчик, но я, похоже, застрял на том, как использовать обработчик для фактического представления данных путем обновления карты / значков на карте.

Карта продолжает ставить маркер на 0,0, а также не позиционирует карту на новом месте, отправленном через обработчик.

   //get GPS latitude and Longitude from service here
    private void displayLatLong() {
        final TextView latitudeView = (TextView) findViewById(R.id.latitude);
        final TextView longitudeView = (TextView) findViewById(R.id.longitude);
        final TextView latitudeCoordsView = (TextView) findViewById(R.id.latitudecoordsView);
        final TextView longitudeCoordsView = (TextView) findViewById(R.id.latitudecoordsView);

        final Handler handler = new Handler();
        handler.post(new Runnable() {
            @Override
            public void run() {
                double latitude = 0.0;
                double longitude = 0.0;

                //latitudeCoords = "not empty"; //debug
                //longitudeCoords = "not empty"; //debug

                if(bound && locationService != null) {
                    latitude = locationService.getLastLatitude();
                    longitude = locationService.getlastLongitude();
                }
                String latitudeStr = String.format(Locale.getDefault(), "%1$, .5f lat", latitude);
                String longitutdeStr = String.format(Locale.getDefault(), "%1$, .5f long", longitude);
                latitudeView.setText(latitudeStr);
                longitudeView.setText(longitutdeStr);

                latCoords = latitude;
                longCoords = longitude;

               // longitudeCoordsView.setText(longitudeCoords); //debug
               // latitudeCoordsView.setText(longitudeCoords); //debug

                handler.postDelayed(this, 1000);
            }
        });
    }

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

        // Get the SupportMapFragment and request notification
        // when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);


        //Bind location service here so it keeps running even if activity is stopped.
        Intent intent = new Intent(this, LocationService.class);
        bindService(intent, connection, Context.BIND_AUTO_CREATE);

        displayDistance();
        displayLatLong();
    }

@Override
    public void onMapReady(GoogleMap map) {
        mMap = map;
        LatLng player= new LatLng(latCoords, longCoords);
        mMap.addMarker(new MarkerOptions().position(player).title("current player position"));//set marker with player position and description
        mMap.moveCamera(CameraUpdateFactory.newLatLng(player)); //move Camera to player position
    }locat

1 Ответ

0 голосов
/ 03 октября 2019

Вам просто нужно обновить карту, как только вы получите местоположение.

Добавьте метод, который обновит карту:

private void updateMapLocation() {
  LatLng player= new LatLng(latCoords, longCoords);
  mMap.addMarker(new MarkerOptions().position(player).title("current player position"));//set marker with player position and description
  mMap.moveCamera(CameraUpdateFactory.newLatLng(player)); //move Camera to player position
}

Затем вызовите этот метод, как только у вас будет latCoords и longCoords заполнены переменные-члены:

//get GPS latitude and Longitude from service here
private void displayLatLong() {
    final TextView latitudeView = (TextView) findViewById(R.id.latitude);
    final TextView longitudeView = (TextView) findViewById(R.id.longitude);
    final TextView latitudeCoordsView = (TextView) findViewById(R.id.latitudecoordsView);
    final TextView longitudeCoordsView = (TextView) findViewById(R.id.latitudecoordsView);

    final Handler handler = new Handler();
    handler.post(new Runnable() {
        @Override
        public void run() {
            double latitude = 0.0;
            double longitude = 0.0;

            if(bound && locationService != null) {
                latitude = locationService.getLastLatitude();
                longitude = locationService.getlastLongitude();
            }
            String latitudeStr = String.format(Locale.getDefault(), "%1$, .5f lat", latitude);
            String longitutdeStr = String.format(Locale.getDefault(), "%1$, .5f long", longitude);
            latitudeView.setText(latitudeStr);
            longitudeView.setText(longitutdeStr);


            latCoords = latitude;
            longCoords = longitude;

            // Add call to update map with location:
            if (latCoords > 0 && longCoords > 0) {
              updateMapLocation()
            }

            handler.postDelayed(this, 1000);
        }
    });
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...