Google Maps API установить маршрут из массива Адаптер нажмите - PullRequest
0 голосов
/ 11 марта 2019

Я пытаюсь построить маршрут с API Google Maps, но у меня большие трудности с отображением линий.

Я следовал примерам API и смог сделать демонстрацию ломаной линии, но когда я принесэто к моему проекту это не появляется.

я получил это на данный момент.

public class Index extends AppCompatActivity implements GoogleMap.OnMyLocationButtonClickListener, GoogleMap.OnMyLocationClickListener, OnMapReadyCallback, ActivityCompat.OnRequestPermissionsResultCallback {
    public static String[] account;

    private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;
    private boolean mPermissionDenied = false;
    private GoogleMap mMap;
    LocationManager locationManager;
    LocationListener locationListener;
    String[][] mobileArray = {
            new String[] {"150 Goyeau St, Windsor, ON N9A 6J5 [3:30]","1g Bubba Kush","Meet at back","3:30pm"},
            new String[] {"2000 Talbot Road West, Windsor, ON N9A 6S4 [4:00]","1oz Rockstar","Watch for dog","4:00pm"},
            new String[] {"350 City Hall Square W, Windsor, ON N9A 6S1 [4:30]","2 pens","Go in the back","4:30pm"}
    };

    public void centreMapOnLocation(Location location, String title){
        LatLng userLocation = new LatLng(location.getLatitude(),location.getLongitude());
        mMap.clear();
        mMap.addMarker(new MarkerOptions().position(userLocation).title(title));
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation,15));

    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            hideSystemUI();
        }
    }
    private void hideSystemUI() {
        View decorView = getWindow().getDecorView();
        decorView.setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_IMMERSIVE
                        | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_FULLSCREEN);
    }
    public LatLng getLocationFromAddress(Context context,String strAddress) {
        Geocoder coder = new Geocoder(context);
        List<Address> address;
        LatLng p1 = null;
        try {
            address = coder.getFromLocationName(strAddress, 5);
            if (address == null) {
                return null;
            }
            Address location = address.get(0);
            p1 = new LatLng(location.getLatitude(), location.getLongitude() );
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        Toast.makeText(context,p1.toString(),Toast.LENGTH_SHORT).show();
        return p1;
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView tVDriver = (TextView)findViewById(R.id.tVDriver);
        tVDriver.setText(account[0]);
        final TextView tVSpecial = (TextView)findViewById(R.id.tVSpecial);
        final TextView tVProduct = (TextView)findViewById(R.id.tVProduct);
        String[] addressArray = new String[mobileArray.length];
        for(int i=0; i<mobileArray.length; i++) {
            addressArray[i] = mobileArray[i][0];
        }
        ArrayAdapter adapter = new ArrayAdapter<String>(this, R.layout.listview, addressArray);
        ListView listView = (ListView) findViewById(R.id.lVDelivery);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?>adapter, View v, int position, long id){
                getLocationFromAddress(Index.this,mobileArray[position][0]);
                tVSpecial.setText(mobileArray[position][2]);
                tVProduct.setText(mobileArray[position][1]);
            }
        });
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
        BackWork bwork = new BackWork(this);
        bwork.execute("directions",null,null);
    }
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        Polyline polyline1 = googleMap.addPolyline(new PolylineOptions()
                .clickable(true)
                .width(5)
                .color(Color.RED)
                .add(new LatLng(42.3149, 83.0364),
                        new LatLng(42.3183, 83.0373)));
        Intent intent = getIntent();
        if (intent.getIntExtra("Place Number",0) == 0 ){
            // Zoom into users location
            locationManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
            locationListener = new LocationListener() {
                @Override
                public void onLocationChanged(Location location) {
                    centreMapOnLocation(location,"Your Location");
                }

                @Override
                public void onStatusChanged(String s, int i, Bundle bundle) {

                }

                @Override
                public void onProviderEnabled(String s) {

                }

                @Override
                public void onProviderDisabled(String s) {

                }
            };
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
                Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                centreMapOnLocation(lastKnownLocation,"Your Location");
            } else {
                ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);
            }
        }
    }
    private void enableMyLocation() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            PermissionUtils.requestPermission(this, LOCATION_PERMISSION_REQUEST_CODE,
                    Manifest.permission.ACCESS_FINE_LOCATION, true);
        } else if (mMap != null) {
            mMap.setMyLocationEnabled(true);
        }
    }
    @Override
    public boolean onMyLocationButtonClick() {
        Toast.makeText(this, "MyLocation button clicked", Toast.LENGTH_SHORT).show();
        return false;
    }
    @Override
    public void onMyLocationClick(@NonNull Location location) {
        Toast.makeText(this, "Current location:\n" + location, Toast.LENGTH_LONG).show();
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode != LOCATION_PERMISSION_REQUEST_CODE) {
            return;
        }
        if (PermissionUtils.isPermissionGranted(permissions, grantResults,
                Manifest.permission.ACCESS_FINE_LOCATION)) {
            enableMyLocation();
        } else {
            mPermissionDenied = true;
        }
    }
    @Override
    protected void onResumeFragments() {
        super.onResumeFragments();
        if (mPermissionDenied) {
            showMissingPermissionError();
            mPermissionDenied = false;
        }
    }
    private void showMissingPermissionError() {
        PermissionUtils.PermissionDeniedDialog
                .newInstance(true).show(getSupportFragmentManager(), "dialog");
    }
}

и для xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:background="@drawable/in_the_weeds"
    android:layout_height="match_parent">

    <include
        layout="@layout/map"
        android:layout_width="match_parent"
        android:layout_height="350dp"
        android:layout_alignParentStart="true"
        android:layout_alignParentBottom="true"
        android:layout_marginStart="0dp"
        android:layout_marginBottom="0dp" />

    <TextView
        android:id="@+id/tVNull"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginStart="20dp"
        android:layout_marginTop="25dp"
        android:background="#80FFFFFF"
        android:text="Driver"
        android:paddingTop="5dp"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:paddingBottom="5dp"
        android:textSize="24sp" />

    <TextView
        android:id="@+id/tVDriver"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentEnd="true"
        android:layout_marginTop="25dp"
        android:layout_marginEnd="20dp"
        android:paddingTop="5dp"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:paddingBottom="5dp"
        android:background="#80FFFFFF"
        android:text="No Driver"
        android:textSize="24sp"/>

    <ListView
        android:id="@+id/lVDelivery"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:background="#80FFFFFF"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginStart="20dp"
        android:layout_marginTop="90dp" />

    <TextView
        android:id="@+id/tVProduct"
        android:layout_width="160dp"
        android:layout_height="200dp"
        android:layout_alignParentTop="true"
        android:layout_alignParentEnd="true"
        android:layout_marginStart="10dp"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="90dp"
        android:layout_marginEnd="20dp"
        android:layout_toRightOf="@+id/lVDelivery"
        android:paddingTop="5dp"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:paddingBottom="5dp"
        android:background="#80FFFFFF"
        android:textSize="24sp"
        android:text="1g - Bubba Hash" />

    <TextView
        android:id="@+id/tVSpecial"
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginStart="20dp"
        android:layout_marginEnd="20dp"
        android:layout_marginTop="300dp"
        android:layout_toRightOf="@+id/tVProduct"
        android:background="#80FFFFFF"
        android:paddingTop="5dp"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:paddingBottom="5dp"
        android:textSize="24sp"
        android:text="TextView" />

</RelativeLayout>

и карты

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/layout">

    <fragment
        android:id="@+id/map"
        class="com.google.android.gms.maps.SupportMapFragment"
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</FrameLayout>

То, что я пытаюсь сделать, - это когда я нажимаю на элемент в адаптере, я хочу, чтобы он нанес на карту курс на карте.

Я уже получил широту и долготу.я получил информацию JSON для уже выполненных шагов.

Это моя асинхронная задача, чтобы вытащить JSON

public class BackWork extends AsyncTask<String,String,String> {
    Context context;
    String type;
    BackWork (Context context){
        this.context = context;
    }

    @Override
    protected String doInBackground(String... params) {
        type = params[0];
        String login_url = "http://ip/website/";
        if(type.equals("login")){
            try {
                login_url = login_url + "api.php?type=login";
                String user = params[1];
                String pass = params[2];
                URL url = new URL(login_url);
                HttpURLConnection urlconn = (HttpURLConnection)url.openConnection();
                urlconn.setRequestMethod("POST");
                urlconn.setDoOutput(true);
                urlconn.setDoInput(true);
                OutputStream out = urlconn.getOutputStream();
                BufferedWriter bWrite = new BufferedWriter(new OutputStreamWriter(out,"UTF-8"));
                String post_data = URLEncoder.encode("user","UTF-8")+"="+URLEncoder.encode(user,"UTF-8")+"&"+URLEncoder.encode("pass","UTF-8")+"="+URLEncoder.encode(pass,"UTF-8");
                bWrite.write(post_data);
                bWrite.flush();
                bWrite.close();
                out.close();
                InputStream in = urlconn.getInputStream();
                BufferedReader bRead = new BufferedReader(new InputStreamReader(in,"iso-8859-1"));
                String result = "";
                String line = "";
                while((line = bRead.readLine()) != null){
                    result += line;
                }
                bRead.close();
                in.close();
                urlconn.disconnect();
                return result;
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else if(type.equals("directions")){
            try {
                login_url = "https://maps.googleapis.com/maps/api/directions/json?origin=494+Aylmer+Ave,+Windsor,+ON+N9A+1T6&destination=City+Hall+Square+E,+Windsor,+ON&key=[APIKEY]";
                URL url = new URL(login_url);
                HttpURLConnection urlconn = (HttpURLConnection)url.openConnection();
                InputStream in = urlconn.getInputStream();
                BufferedReader bRead = new BufferedReader(new InputStreamReader(in,"iso-8859-1"));
                String result = "";
                String line = "";
                while((line = bRead.readLine()) != null){
                    result += line;
                }
                bRead.close();
                in.close();
                urlconn.disconnect();
                return result;
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onPreExecute(){
    }

    @Override
    protected void onPostExecute(String result){
        String array[] = new String[12];
        if(type.equals("login")) {
            if (result.equals("-1")) {
                Toast.makeText(context, "No such account", Toast.LENGTH_SHORT).show();
            } else {
                try {
                    JSONObject jresponse = new JSONObject(result);
                    array[0] = jresponse.getString("user");
                    Index.account = array;
                    Toast.makeText(context, "Welcome, "+array[0], Toast.LENGTH_SHORT).show();
                } catch (JSONException e) {
                    Toast.makeText(context, "Unknown login Error: "+e, Toast.LENGTH_SHORT).show();
                    e.printStackTrace();
                }
            }
        }else if(type.equals("directions")){
            if (result.equals("-1")) {
                Toast.makeText(context, "Address not found", Toast.LENGTH_SHORT).show();
            } else {
                try {
                    JSONObject json = new JSONObject(result);
                    JSONArray routes = json.getJSONArray("routes").getJSONObject(0).getJSONArray("legs").getJSONObject(0).getJSONArray("steps");
                    Toast.makeText(context, "JSON "+routes, Toast.LENGTH_SHORT).show();
                } catch (JSONException e) {
                    Toast.makeText(context, "Unknown gmaps error "+e, Toast.LENGTH_SHORT).show();
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    protected void onProgressUpdate(String... values){

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