【问题标题】:Add Markers to map from mysql using volley使用 volley 添加标记以从 mysql 映射
【发布时间】:2018-12-14 18:06:40
【问题描述】:

我需要在地图上显示我的“Npc”标记,但 onMapReady() 中的 npcList 是空的。如何将我的 Npc 从 getNPC() npcList 正确放入 onMapReady() npcList 中,然后在地图上显示标记

我的 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();
        }
    }

}

我的 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;
}

}

我正在从 db 中检索正确的值,如下图所示

image

请帮我卡住

【问题讨论】:

    标签: android google-maps android-volley android-json


    【解决方案1】:

    试试这个,在添加到您的数组列表后移动您的循环以添加标记作为响应

    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);
        }
    

    希望对你有帮助。

    【讨论】:

    • 我认为解析你的 JSON 时出错,我刚刚看到你的日志,它在 JSONException 上,所以它在出错。您可以发布来自网络服务的响应吗? @PhilippSch
    • link@ErwinKurniawan
    • 是的,您在解析 json 时出错。我编辑了解析你的 json 的答案,请尝试一下
    • 我刚刚做了,现在没有错误但仍然没有标记
    • 好了,解析好了。标记有错误吗?
    【解决方案2】:

    我对 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);
    }
    

    【讨论】:

    • 看起来npc.getLongs 已更改为npc.getDoubles,从而消除了有损转换。
    • 但是@ErwinKurniawan
    猜你喜欢
    • 1970-01-01
    • 2017-10-28
    • 1970-01-01
    • 1970-01-01
    • 2015-09-15
    • 2014-12-24
    • 2015-12-21
    • 2012-07-20
    • 1970-01-01
    相关资源
    最近更新 更多