Android Studio无法使用json绘制标记 [英] Android Studio unable to plot marker using json

查看:134
本文介绍了Android Studio无法使用json绘制标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用json绘制标记,其中没有显示标记。这里是我的地图活动代码。

I am trying to plot marker using json in which marker is not showing.here is my code of map activity.

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback  {
    public 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);
    }


    public void onMapSearch (View view) throws IOException {

        //hide button when button is pressed
        InputMethodManager inputManager = (InputMethodManager) getSystemService(this.INPUT_METHOD_SERVICE);
        inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

        //preview the entered address as an Tost in bar
        EditText locationSearch = (EditText) findViewById(R.id.editText);
        String location = locationSearch.getText().toString();

        //this will animate camera and zoom 12.0f
        mMap.animateCamera(CameraUpdateFactory.zoomTo(12.0f));



        //further address search codes
        List<Address> addressList = null;

        //if nothing will be entered in the edit-text will not show a toast rather than crashing of thekha app
        if (locationSearch.getText().toString().equals("")){
            Toast.makeText(this,"Bitch please enter A Value",Toast.LENGTH_LONG).show();
        }
        else {

            //process of exception handling and finding location
            if (location != null || !location.equals("")) {
                Geocoder geocoder = new Geocoder(this);
                try {
                    addressList = geocoder.getFromLocationName(location, 1);
                } catch (IOException e) {
                    e.printStackTrace();
                  }
                //if address is greater than one then these processes will happen

                if(addressList.size()>0) {
                    Address address = addressList.get(0);
                    LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
                    mMap.addMarker(new MarkerOptions()
                            .position(latLng)
                            .title(location + " is Here- ")
                            .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
                    mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));

                    Toast.makeText(this, location+" is here, Zoom In or Zoom Out to make your Thekha Visible ", Toast.LENGTH_LONG)
                            .show(); //popup type to show entered data
                }
                else {
                    //process where entered entry will not gonna find , this will gonna a toast to show popup

                    Toast.makeText(this,"Entered Address Not Found", Toast.LENGTH_LONG).show();

                }
            }

        }
    }



    private void setUpMap (){
        final MapsActivity that = this;
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    retriveAndAddMarker();
                }catch (IOException e){
                    Toast.makeText(that,"Can not fetch data",Toast.LENGTH_LONG).show();
                }

            }
        });
    }

    protected void retriveAndAddMarker () throws IOException {
        final MapsActivity that = this;

        HttpURLConnection conn = null;
        final StringBuilder json = new StringBuilder();
        try {
            //connect to the web service
            URL url = new URL("http://www.loofre.com/api-for-webservice/?debug=true&action=getLocations");
            conn = (HttpURLConnection) url.openConnection();
            InputStreamReader in = new InputStreamReader(conn.getInputStream());
            //This will read the json data into string builder
            int read;
            char[] buff = new char[1024];
            while ((read = in.read(buff)) != -1) {
                json.append(buff, 0, read);
            }
        } catch (IOException e) {
            Toast.makeText(this, "Error connecting to Service", Toast.LENGTH_LONG).show();
            throw new IOException("Error Connecting to service ", e);

        } finally {
            if (conn != null)

                conn.disconnect();
            Toast.makeText(this,"Disconnected",Toast.LENGTH_LONG).show();
        }


        //create marker for the onMapReady over main thekha app
        // Must run this on this on the UI thread since its the UI operation.

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {

                    Toast.makeText(that, "Connection SuccessFull", Toast.LENGTH_LONG).show();
                    createMarkerFromJson(json.toString());
                }catch (JSONException e){
                    Toast.makeText(that,"",Toast.LENGTH_LONG).show();
                }
            }
        });

    }

    void createMarkerFromJson (String json) throws JSONException {
        // de-derialize the json string into an array of objects


            JSONArray jsonArray = new JSONArray(json);
            for (int i =0; i<jsonArray.length(); i++){
                //create marker of each place in the json data
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                mMap.addMarker(new MarkerOptions()
                             .title(jsonObject.getString("name"))
                                .snippet(Integer.toString((jsonObject.getInt("address"))))
                               .position(new LatLng(
                                       jsonObject.getJSONArray("latlang").getDouble(0),
                                       jsonObject.getJSONArray("latlang").getDouble(0)

                                       )
                               )
                );

            }

        }

    //OnReady map starts here when we can enter or add Marker to the map
    @Override
    public void onMapReady(GoogleMap googleMap) {
       mMap = googleMap;

        setUpMap();
        // no 1 marker
        LatLng dwarka = new LatLng(28.570317,77.32182);
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(dwarka, 13));
        mMap.addMarker(new MarkerOptions()
                       .title("Wine Beer Liquor Shop, Sector 18, Noida")
                        .snippet("Sector 18, Near Centre Stage Mall, Noida")
                           .position( dwarka ));
        //no 2 marker
        LatLng OPG_world_School = new LatLng(28.581074,77.314349);
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(OPG_world_School,13));
        mMap.addMarker(new MarkerOptions()
                        .title("Wine Beer Liquor Shop, Sector 15, Noida")
                           .snippet("Basoya Complex, Sector 15, Near Wipro, Noida")
                              .position(OPG_world_School));
        //no 3 marker
        LatLng sector27 = new LatLng(28.581074,77.314349);
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sector27,13));
        mMap.addMarker(new MarkerOptions()
                .title("Wine Beer Liquor Shop, sector 27, Noida")
                .snippet("Dharam Pali Palace, Sector 27, Near Vinayak Hospital, Noida")
                .position(sector27));
        //no 4 marker
        LatLng gurgramamb = new LatLng(28.504865,77.094588); // tobe edited
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(gurgramamb,13));
        mMap.addMarker(new MarkerOptions()
                      .title("Discovery Wines")
                       .snippet("Discovery Wines, Ambience Mall, Gurgaon")
                        .position(gurgramamb));

        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission
                (this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //  int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        //tool bar and other tool related on map uiSettings
        mMap.setMyLocationEnabled(true);
        mMap.getUiSettings().setZoomControlsEnabled(true);
        mMap.getUiSettings().setMapToolbarEnabled(true);
        mMap.getUiSettings().setMyLocationButtonEnabled(true);

    }
}


推荐答案

你的问题在 retriveAndAddMarker 上。您正在使用应该使用AsyncTask运行的网络线程拨打电话。

Your issue is on retriveAndAddMarker. You're making a call using network thread that supposed to be run using AsyncTask.


网络操作可能涉及不可预知的延迟。为了防止这种情况导致糟糕的用户体验,请始终在UI的单独线程上执行网络操作。 AsyncTask类提供了一种最简单的方法来从UI线程中触发新任务 - Android开发人员[在单独线程上执行网络操作]

您可以尝试添加以下代码片段:

You can try adding this snippet:

private class RetrieveMarkerTask extends AsyncTask<StringBuilder, Void, StringBuilder> {

    private Context context;

    public RetrieveMarkerTask(Context context){
        this.context = context;
    }

    @Override
    protected StringBuilder doInBackground(StringBuilder... stringBuilders) {
        HttpURLConnection conn = null;
        final StringBuilder json = new StringBuilder();
        try {
            //connect to the web service
            URL url = new URL("http://www.loofre.com/api-for-webservice/?debug=true&action=getLocations");
            conn = (HttpURLConnection) url.openConnection();
            InputStreamReader in = new InputStreamReader(conn.getInputStream());
            //This will read the json data into string builder
            int read;
            char[] buff = new char[1024];
            while ((read = in.read(buff)) != -1) {
                json.append(buff, 0, read);
            }
        } catch (IOException e) {
            return null;
        } finally {
            if (conn != null)
                conn.disconnect();

        }
        return json;
    }

    @Override
    protected void onPostExecute(StringBuilder stringBuilder) {
        super.onPostExecute(stringBuilder);

        if(null != stringBuilder){
            try {
                ((MapsActivity)context).createMarkerFromJson(stringBuilder.toString());
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
}

在您的 retriveAndAddMarker()中,删除此方法中的所有行,并用下面的行替换。

And in your retriveAndAddMarker(), remove all those lines inside this method and replace with line below.

protected void retriveAndAddMarker (){
    //remove all the previous code
    new RetrieveMarkerTask(this).execute();
}

注意:
我简单地创建基于你的代码的AsyncTask,所以我不确定它是否工作。您需要自行调试。

Note: I simply created the AsyncTask based on your code, so I am not sure if it is working or not. You need to debug it on your own.

这篇关于Android Studio无法使用json绘制标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆