Добавить файл геоджона на мою карту в приложении для Android - PullRequest
0 голосов
/ 09 января 2019

Я очень новичок в Android Studio и Java. Я пытаюсь сделать приложение карты с некоторыми интересными точками. Точки - это файл геойсона. Я прочитал пример Google и объяснение на их веб-сайте ( Google Maps Android GeoJSON Utility ), но у меня есть некоторые ошибки в моем коде. Первая ошибка связана с методом getmMap (ошибка: невозможно найти метод символа getnMap ()). Второе решение, которое я нахожу, касается файла, которому не нужно расширение (geojson). Я делаю папку в rs с именем raw и добавляю файл geojson внутрь.

Полный код MapsActivity.java

package com.example.vassilis.goldman_find_atm;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.maps.android.data.geojson.GeoJsonLayer;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private static final int MY_REQUEST_INT = 177;
    private GoogleMap mMap;

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


    /**
     * 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;

        //Enable Current Location:

        //Here We want to check the permission of Location - GPS
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){

                requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_FINE_LOCATION},MY_REQUEST_INT);
            }

            return;
        }else {
            //Here the code of Grand Permission
            mMap.setMyLocationEnabled(true);

        }

        // Add a marker in Sydney and move the camera
        /*LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));*/


        GeoJsonLayer layer = new GeoJsonLayer(getmMap(), R.raw.nbg_bank.geojson ,
                getApplicationContext());
        layer.addLayerToMap();
    }
}

ошибка : невозможно найти метод символа getmMap ()

Я изменяю getmMap () на mMap и система: Surround с try / catch. Я изменяю это, и код изменяется на. Построение кода закончилось без проблем, но на карте я не увидел точек.

С

GeoJsonLayer layer = new GeoJsonLayer(mMap, R.raw.nbg_bank,
                getApplicationContext());

        layer.addLayerToMap();

До

GeoJsonLayer layer = null;
        try {
            layer = new GeoJsonLayer(mMap, R.raw.nbg_bank,
                    getApplicationContext());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }

        layer.addLayerToMap();

enter image description here

Android Studio

1 Ответ

0 голосов
/ 24 января 2019

Убедитесь, что формат файла json правильный.

Проверьте этот geojson код файла:

{
    "type": "FeatureCollection",
    "features": [{

        "type": "Feature",
         "geometry": {
             "type": "Point",
             "coordinates": 
                [102.0, 0.5]
         },
         "properties": {
         "prop0": "value0"
         }
        }, {

           "type": "Feature",
           "geometry": {
               "type": "LineString",
               "coordinates": [
                 [102.0, 0.0],
                 [103.0, 1.0],
                 [104.0, 0.0],
                 [102.0, 0.0]
                 ]
               },
               "properties": {
                "prop0": "value0",
                "prop1": 0.0
               }
        }
    ]
}

Для получения дополнительной информации см .: https://cran.r -project.org / web / packages / geojsonR / vignettes / the_geojsonR_package.html

Чтобы проверить, является ли ваш файл GeoJson правильным или нет, посетите: http://geojsonlint.com/

...