Добавить маркеры на карту из MySQL, используя залп - PullRequest
0 голосов
/ 14 декабря 2018

Мне нужно показать мои маркеры 'Npc' на карте, но список npcList в onMapReady () пуст.Как правильно указать мой Npcs из getNPC () npcList в onMapReady () npcList, а затем отобразить маркеры на карте

my onMapReady ():

public void onMapReady(GoogleMap googleMap) {
    mGoogleMap = googleMap;
    mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);


    //zoom map camera
    // Get LocationManager object
    LocationManager locationManager = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);

    // Create a criteria object to retrieve provider
    Criteria criteria = new Criteria();

    // Get the name of the best provider
    String provider = (locationManager).getBestProvider(criteria, true);


    Location myLocation = (locationManager).getLastKnownLocation(provider);

    // myLastLoc = myLocation;
    if (myLocation != null) {
        //latitude of location
        double myLatitude = myLocation.getLatitude();

        //longitude og location
        double myLongitude = myLocation.getLongitude();

        LatLng latLon = new LatLng(myLatitude, myLongitude);
        mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLon, 17));
    }
    mGoogleMap.setMyLocationEnabled(true);//koumpi gia location
    buildGoogleApiClient(); // mallon mpilia

    // locationManager.requestLocationUpdates(provider,1000,1f,com.google.android.gms.location.LocationListener);

    npcList = new ArrayList<Npc>();

    getNPC();
    for(Npc mynpc:npcList) {

        if (!npcList.isEmpty()) {

            LatLng loc = new LatLng(mynpc.getNpclat(), mynpc.getNpclng());
            String name = mynpc.getNpcname();
            mGoogleMap.addMarker(new MarkerOptions()
                    .position(loc)
                    .title(name));

        } else {
            Toast.makeText(getActivity().getApplicationContext(), "npcList is empty", Toast.LENGTH_LONG).show();
        }
    }

}

my getNPC ():

    private void getNPC() {
    StringRequest stringRequest = new StringRequest(Request.Method.POST, Constants.URL_NPC_GET,
            new com.android.volley.Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject obj = new JSONObject(response);
                        Log.i("GAME_TAG", "response caught");
                        boolean error = obj.getBoolean("error");

                        if (!error) {
                            Log.i("GAME_TAG", "response showing return no error");

                            //converting the string to json array object
                            JSONArray array = obj.getJSONArray("results");

                            Log.i("GAME_TAG", "response has " + array.length() + " npcs");

                            //traversing through all the object
                            for (int i = 0; i < array.length(); i++) {

                                //getting npc object from json array
                                JSONObject npc = array.getJSONObject(i);
                                //adding the npc to npc list
                                npcList.add(new Npc(
                                        npc.getInt("npcid"),
                                        npc.getInt("userid"),
                                        npc.getString("npcname"),
                                        npc.getString("npcwelcome"),
                                        (float) npc.getLong("npclat"),
                                        (float) npc.getLong("npclng")

                                ));

                            Log.i("GAME_TAG", "now arraylist has " + npcList.size() + " npcs");

                            Npc mynpc = npcList.get(i);
                                LatLng loc = new LatLng(mynpc.getNpclat(), mynpc.getNpclng());
                                String name = mynpc.getNpcname();
                                mGoogleMap.addMarker(new MarkerOptions()
                                        .position(loc)
                                        .title(name));
                                Log.i("GAME_TAG", "npc name "+ name+"  " +loc);
                            }
                            Log.i("GAME_TAG", "if this sentence showing and still no marker, lets try adding only one marker");

                            LatLng loc = new LatLng(npcList.get(0).getNpclat(), npcList.get(0).getNpclng());
                            String name = npcList.get(0).getNpcname();
                            mGoogleMap.addMarker(new MarkerOptions()
                                    .position(loc)
                                    .title(name));

                            Log.i("GAME_TAG", "if this sentence showing and with one marker, something wrong with the loop");
                        } else {
                            Log.i("GAME_TAG", "response showing return with error");
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new com.android.volley.Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(getActivity().getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
                }
            });
    RequestHandler.getInstance(getActivity()).addToRequestQueue(stringRequest);
}

мой класс NPC:

package com.example.game1;

public class Npc {

private int npcid;
private int userid;
private String npcname;
private  String npcwelcome;
private float npclat;
private float npclng;

public Npc(int npcid,int userid,String npcname,String npcwelcome,float npclat,float npclng){

    this.npcid = npcid;
    this.userid = userid;
    this.npcname = npcname;
    this.npcwelcome = npcwelcome;
    this.npclat = npclat;
    this.npclng = npclng;

}

public int getNpcid() {
    return npcid;
}

public int getUserid() {
    return userid;
}

public String getNpcname() {
    return npcname;
}

public String getNpcwelcome() {
    return npcwelcome;
}

public float getNpclat() {
    return npclat;
}

public float getNpclng() {
    return npclng;
}

}

im retrievingправильные значения в дБ, как вы можете видеть на изображении ниже

изображение

, пожалуйста, помогите мне застрял

Ответы [ 2 ]

0 голосов
/ 14 декабря 2018

Я сделал несколько изменений в getNPC (), и теперь он работает, вот код:

   private void getNPC() {
    StringRequest stringRequest = new StringRequest(Request.Method.POST, 
Constants.URL_NPC_GET,
            new com.android.volley.Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject obj = new JSONObject(response);
                        Log.i("GAME_TAG", "response caught");
                        boolean error = obj.getBoolean("error");

                        if (!error) {
                            Log.i("GAME_TAG", "response showing return no error");

                            //converting the string to json array object
                            JSONArray array = obj.getJSONArray("results");

                            Log.i("GAME_TAG", "response has " + array.length() + " npcs");

                            //traversing through all the object
                            for (int i = 0; i < array.length(); i++) {

                                //getting npc object from json array
                                JSONObject npc = array.getJSONObject(i);
                                //adding the npc to npc list
                                npcList.add(new Npc(
                                        npc.getInt("npcid"),
                                        npc.getInt("userid"),
                                        npc.getString("npcname"),
                                        npc.getString("npcwelcome"),
                                        (float) npc.getDouble("npclat"),
                                        (float) npc.getDouble("npclng")

                                ));

                            Log.i("GAME_TAG", "now arraylist has " + npcList.size() + 
 " npcs");

                            Npc mynpc = npcList.get(i);
                                LatLng loc = new LatLng(mynpc.getNpclat(), 
 mynpc.getNpclng());
                                String name = mynpc.getNpcname();
                                mGoogleMap.addMarker(new MarkerOptions()
                                        .position(loc)
                                        .title(name));
                                Log.i("GAME_TAG", "npc name "+ name+"  " +loc);
                            }
                            Log.i("GAME_TAG", "if this sentence showing and still no 
 marker, lets try adding only one marker");

                            LatLng loc = new LatLng(npcList.get(0).getNpclat(), 
    npcList.get(0).getNpclng());
                            String name = npcList.get(0).getNpcname();
                            mGoogleMap.addMarker(new MarkerOptions()
                                    .position(loc)
                                    .title(name));

                            Log.i("GAME_TAG", "if this sentence showing and with one marker, something wrong with the loop");
                        } else {
                            Log.i("GAME_TAG", "response showing return with error");
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new com.android.volley.Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(getActivity().getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
                }
            });
    RequestHandler.getInstance(getActivity()).addToRequestQueue(stringRequest);
}
0 голосов
/ 14 декабря 2018

попробуйте это, переместите ваш цикл для добавления маркера в ответ после добавления к вашему списку массивов

public void onMapReady(GoogleMap googleMap) {
    mGoogleMap = googleMap;
    mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);


    //zoom map camera
    // Get LocationManager object
    LocationManager locationManager = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);

    // Create a criteria object to retrieve provider
    Criteria criteria = new Criteria();

    // Get the name of the best provider
    String provider = (locationManager).getBestProvider(criteria, true);


    Location myLocation = (locationManager).getLastKnownLocation(provider);

    // myLastLoc = myLocation;
    if (myLocation != null) {
        //latitude of location
        double myLatitude = myLocation.getLatitude();

        //longitude og location
        double myLongitude = myLocation.getLongitude();

        LatLng latLon = new LatLng(myLatitude, myLongitude);
        mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLon, 17));
    }
    mGoogleMap.setMyLocationEnabled(true);//koumpi gia location
    buildGoogleApiClient(); // mallon mpilia

    // locationManager.requestLocationUpdates(provider,1000,1f,com.google.android.gms.location.LocationListener);

    npcList = new ArrayList<Npc>();

    getNPC();

}

ваш getnpc ()

private void getNPC() {
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constants.URL_NPC_GET,
                new com.android.volley.Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject obj = new JSONObject(response);
                            Log.i("GAME_TAG", "response caught");
                            boolean error = obj.getBoolean("error");

                            if (!error) {
                                Log.i("GAME_TAG", "response showing return no error");

                                //converting the string to json array object
                                JSONArray array = obj.getJSONArray("results");

                                Log.i("GAME_TAG", "response has " + array.length() + " npcs");

                                //traversing through all the object
                                for (int i = 0; i < array.length(); i++) {

                                    //getting npc object from json array
                                    JSONObject npc = array.getJSONObject(i);
                                    //adding the npc to npc list
                                    npcList.add(new Npc(
                                            npc.getInt("npcid"),
                                            npc.getInt("userid"),
                                            npc.getString("npcname"),
                                            npc.getString("npcwelcome"),
                                            npc.getLong("npclat"),
                                            npc.getLong("npclng")

                                    ));
                                }
                                Log.i("GAME_TAG", "now arraylist has " + npcList.size() + " npcs");

                                for (Npc mynpc : npcList) {
                                    LatLng loc = new LatLng(mynpc.getNpclat(), mynpc.getNpclng());
                                    String name = mynpc.getNpcname();
                                    mGoogleMap.addMarker(new MarkerOptions()
                                            .position(loc)
                                            .title(name));
                                }
                                Log.i("GAME_TAG", "if this sentence showing and still no marker, lets try adding only one marker");

                                LatLng loc = new LatLng(npcList.get(0).getNpclat(), npcList.get(0).getNpclng());
                                String name = npcList.get(0).getNpcname();
                                mGoogleMap.addMarker(new MarkerOptions()
                                        .position(loc)
                                        .title(name));

                                Log.i("GAME_TAG", "if this sentence showing and with one marker, something wrong with the loop");
                            } else {
                                Log.i("GAME_TAG", "response showing return with error");
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new com.android.volley.Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(getActivity().getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
                    }
                });
        RequestHandler.getInstance(getActivity()).addToRequestQueue(stringRequest);
    }

Надеюсь, это поможет.

...