如何在Android

时间:2016-12-29 04:57:35

标签: android google-maps driving-directions

我有一个网络应用程序,我们在其中添加lat和lng,在网络中它清楚地显示了地图中的行车路线。我已经使用json向android发送相同的详细信息,包括api,lat和经度。但在Android应用程序中,地图没有显示正确的路径。

这是我的地图活动

public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {

    private GoogleMap mMap;
    LatLng latLng;
    private SharedPreferenceHelper sharedPreferenceHelper;
    private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
    MyAlertDialogFragment newFragment;
    public final String BEFORE_BUS_POSTION = "BEFORE_BUS_POSTION";
    public final String AFTER_BUS_POSTION = "AFTER_BUS_POSTION";
    public final String CURRENT_BUS_POSTION = "CURRENT_BUS_POSTION";

    public final String GREEN_COLOR_CODE = "#228b22";
    public final String ORANGE_COLOR_CODE = "#C56E00";


    private String[] mNavigationDrawerItemTitles;
    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    Toolbar toolbar;
    private CharSequence mDrawerTitle;
    private CharSequence mTitle;
    android.support.v7.app.ActionBarDrawerToggle mDrawerToggle;
    private ProgressDialog progress;
    int count = 0;

        @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        mTitle = mDrawerTitle = getTitle();
        mNavigationDrawerItemTitles= getResources().getStringArray(R.array.navigation_drawer_items_array);
       ....


        sharedPreferenceHelper = new SharedPreferenceHelper(getApplicationContext());
        if (!sharedPreferenceHelper.getBooleanSharedPreferenceName("isRegistred")) {
            RegisterGCM();
        }
        sharedPreferenceHelper.WriteBooleanPreference("notification", true);

        /*Sharedpreference check wheather  app is running for firsttime.*/
        if (!sharedPreferenceHelper.getBooleanSharedPreferenceName("isfirsttime")) {
            sharedPreferenceHelper.WriteBooleanPreference("isfirsttime", true);
            sharedPreferenceHelper.WriteStringPreference("email", getIntent().getStringExtra("email"));
            sharedPreferenceHelper.WriteBooleanPreference("ringtone", true);
            sharedPreferenceHelper.WriteBooleanPreference("notification", true);
        }

        FragmentManager fm = getSupportFragmentManager();
        SupportMapFragment supportMapFragment =  SupportMapFragment.newInstance();
        fm.beginTransaction().replace(R.id.content_frame, supportMapFragment).commit();
        supportMapFragment.getMapAsync(this);
    }
    private class DrawerItemClickListener implements ListView.OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            selectItem(position);
        }

    }

    private void selectItem(int position) {

        AboutFragment aboutfragment = null;
        InfoFragment infofragment = null;
        switch (position) {
            case 0:
                startActivity(new Intent(this, MapsActivity.class));
                break;
            case 1:
                aboutfragment = new AboutFragment();
                break;
            case 2:
                infofragment= new InfoFragment();
                break;

            default:
                break;
        }

        if (aboutfragment != null) {
            FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction().replace(R.id.content_frame, aboutfragment).commit();

            mDrawerList.setItemChecked(position, true);
            mDrawerList.setSelection(position);
            setTitle(mNavigationDrawerItemTitles[position]);
            mDrawerLayout.closeDrawer(mDrawerList);

        }else if (infofragment != null) {
            FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction().replace(R.id.content_frame, infofragment).commit();

            mDrawerList.setItemChecked(position, true);
            mDrawerList.setSelection(position);
            setTitle(mNavigationDrawerItemTitles[position]);
            mDrawerLayout.closeDrawer(mDrawerList);

        } else {
            Log.e("MapActivity", "Error in creating fragment");
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }    
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void setTitle(CharSequence title) {
        mTitle = title;
        getSupportActionBar().setTitle(mTitle);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        mDrawerToggle.syncState();
    }

    void setupToolbar(){
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
    }

    void setupDrawerToggle(){
        mDrawerToggle = new android.support.v7.app.ActionBarDrawerToggle(this,mDrawerLayout,toolbar,R.string.app_name, R.string.app_name);
        //This is necessary to change the icon of the Drawer Toggle upon state change.
        mDrawerToggle.syncState();
    }
    private void RegisterGCM() {

        Log.i("HomeActivity", "This device is not supported.");
        if (checkPlayServices()) {

            // Start IntentService to register this application with GCM.
            Intent intent = new Intent(this, RegistrationIntentService.class);
            startService(intent);
        }

    }

    private boolean checkPlayServices() {
        GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
        int resultCode = apiAvailability.isGooglePlayServicesAvailable(this);
        if (resultCode != ConnectionResult.SUCCESS) {
            if (apiAvailability.isUserResolvableError(resultCode)) {
                apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST)
                        .show();
            } else {
                if(sharedPreferenceHelper.getBooleanSharedPreferenceName("googleplayservice")) {
                    showDialog();
                }
                Log.i("HomeActivity", "This device is not supported.");
            }
            return false;
        }
        return true;
    }    
    void showDialog() {
        newFragment = MyAlertDialogFragment.newInstance(R.string.google_play_service_not_found);
        newFragment.show(getSupportFragmentManager(), "dialog");
    }

    public static class MyAlertDialogFragment extends DialogFragment {

        AlertDialog alert;

        public static MyAlertDialogFragment newInstance(int title) {
            MyAlertDialogFragment frag = new MyAlertDialogFragment();
            Bundle args = new Bundle();
            args.putInt("title", title);
            frag.setArguments(args);
            return frag;
        }    
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            int title = getArguments().getInt("title");

            return new AlertDialog.Builder(getActivity())
                    .setIcon(R.drawable.ic_info_black_24dp)
                    .setTitle(title)
                    .setMessage(R.string.google_play_service_not_found_message)
                    .setPositiveButton("Ok",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int whichButton) {
                                    ((MapsActivity)getActivity()).doPositiveClick();
                                }
                            }
                    )
                    .setNegativeButton("Don't show again",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int whichButton) {
                                    ((MapsActivity)getActivity()).doNegativeClick();
                                }
                            }
                    ).create();  
        }
    }

    public void doPositiveClick() {
        Log.i("FragmentAlertDialog", "Positive click!");
        newFragment.dismiss();
    }

    public void doNegativeClick() {
        newFragment.dismiss();
        sharedPreferenceHelper.WriteBooleanPreference("googleplayservice", true);
        Log.i("FragmentAlertDialog", "Negative click!");
    }
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        progress=new ProgressDialog(this);
        progress.setMessage("Map Loading");
        progress.show();
        progress.setCanceledOnTouchOutside(false);
        final Handler ha=new Handler();

        ha.postDelayed(new Runnable() {

            @Override
            public void run() {
                //call function
                setLocationFromServerWithRoute();
                ha.postDelayed(this, 2000);
            }
        }, 10000);

        // 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));*/
    }
    private void setLocationFromServerWithRoute() {

        RequestQueue queue = Volley.newRequestQueue(this);

        String email = new SharedPreferenceHelper(getApplicationContext()).getStringSharedPreferenceName("email");
        String url = LoginActivity.URL+ "read.jsp?email="+email;
        Log.d("email",email);

        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>(){
                    @Override
                    public void onResponse(String response) {

                        JSONArray array = new JSONArray();
                        Log.d("Response 10 secs",response);
                        try {
                            array = new JSONArray(response);
                            mMap.clear();
                            for(int n = 0; n < array.length()-1; n++) {

                                JSONObject jsonObject = array.getJSONObject(n);
                                JSONObject jsonObjectNext = array.getJSONObject(n+1);
                                LatLng latLng = new LatLng(jsonObject.getDouble("latitude"), jsonObject.getDouble("longitude"));
                                LatLng latLngNext = new LatLng(jsonObjectNext.getDouble("latitude"), jsonObjectNext.getDouble("longitude"));
                                String address = jsonObject.getString("routename");   
                                Log.d("Response",response);
                                if(jsonObjectNext.getString("busPosition").equals(CURRENT_BUS_POSTION) && n < array.length()-2 ) {
                                    jsonObjectNext = array.getJSONObject(n+2);
                                    latLngNext = new LatLng(jsonObjectNext.getDouble("latitude"), jsonObjectNext.getDouble("longitude"));

                                }                                    if(jsonObject.getString("busPosition").equals(CURRENT_BUS_POSTION)){

                                    mMap.addMarker(new MarkerOptions().position(latLng).title("" + address)
                                                .icon(BitmapDescriptorFactory.fromResource(R.drawable.bus_blue)));

                                    Log.d("CURRENT_BUS_POSTION","REACHED");

                                }else if(jsonObject.getString("busPosition").equals(AFTER_BUS_POSTION)){

                                    if(jsonObject.getBoolean("isBusStop")) {
                                        mMap.addMarker(new MarkerOptions().position(latLng).title("" + address)
                                                .icon(BitmapDescriptorFactory.fromResource(R.drawable.bus_orange)));
                                    }
                                    mMap.addPolyline(new PolylineOptions()
                                            .add(latLng,latLngNext)
                                            .width(5)
                                            .color(Color.parseColor(ORANGE_COLOR_CODE)));

                                }else if(jsonObject.getString("busPosition").equals(BEFORE_BUS_POSTION)){

                                    if(jsonObject.getBoolean("isBusStop")) {
                                        mMap.addMarker(new MarkerOptions().position(latLng).title("" + address)
                                                .icon(BitmapDescriptorFactory.fromResource(R.drawable.bus_green)));
                                    }
                                    mMap.addPolyline(new PolylineOptions()
                                            .add(latLng,latLngNext)
                                            .width(5)
                                            .color(Color.parseColor(GREEN_COLOR_CODE)));    
                                }    
                            }

                            JSONObject jsonObject = array.getJSONObject(array.length() - 1);
                            LatLng latLng = new LatLng(jsonObject.getDouble("latitude"), jsonObject.getDouble("longitude"));
                            String address = jsonObject.getString("routename");

                            if (jsonObject.getString("busPosition").equals(CURRENT_BUS_POSTION)) {
                                mMap.addMarker(new MarkerOptions().position(latLng).title("" + address)
                                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.bus_blue)));
                            } else if (jsonObject.getString("busPosition").equals(AFTER_BUS_POSTION) && jsonObject.getBoolean("isBusStop")) {
                                mMap.addMarker(new MarkerOptions().position(latLng).title("" + address)
                                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.bus_orange)));
                            } else if (jsonObject.getString("busPosition").equals(BEFORE_BUS_POSTION) && jsonObject.getBoolean("isBusStop")) {
                                mMap.addMarker(new MarkerOptions().position(latLng).title("" + address)
                                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.bus_green)));
                            }
                            ;
                    if(count < 2) {

                        Log.v("count",""+count);
                        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
                        mMap.animateCamera(CameraUpdateFactory.zoomTo(16.0f));
                        if(count == 1){
                            progress.hide();
                        }
                        }
                            count ++;
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }      
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                 Toast.makeText(getApplicationContext(),"Error:"+error.getMessage(),Toast.LENGTH_SHORT).show();
            }
        });
        queue.add(stringRequest);    
    }


    private void setLocationFromServer() {  
        RequestQueue queue = Volley.newRequestQueue(this);    
        String email = new SharedPreferenceHelper(getApplicationContext()).getStringSharedPreferenceName("email");
        String url = LoginActivity.URL+ "read.jsp?email="+email;

        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>(){
                    @Override
                    public void onResponse(String response) {
                        Toast.makeText(getApplicationContext(),"Response:"+response,Toast.LENGTH_SHORT).show();
                        Log log = null;
                        log.v("response",""+response);
                        JSONObject jsonObject = null;
                        Double param1 = 0.0;
                        Double param2 = 0.0;
                        Long datecreated = null;
                        String dateCreated = null;
                        Date dateCREATED = null, twoHOURDate;

                        Calendar cal = Calendar.getInstance();
                        cal.add(Calendar.HOUR, -2);
                        Date twoHourBack = cal.getTime();
                        Log.v("twoHourBack::", "" + twoHourBack);
                        Toast.makeText(getApplicationContext(),"+twoHourBack:"+twoHourBack,Toast.LENGTH_SHORT).show();


                        JSONObject jsonObjectData = new JSONObject();
                        JSONArray array = new JSONArray();
                        try {
                            jsonObjectData = new JSONObject(response);
                            array = jsonObjectData.getJSONArray("route");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }


                        ArrayList<BusRoute> arrayList = new ArrayList();
                        for(int n = 0; n < array.length(); n++) {
                            try {
                                JSONObject object = array.getJSONObject(n);
                                BusRoute busRoute = new BusRoute();
                                busRoute.setId(object.getString("routeID"));
                                busRoute.setLatitude(object.getString("latitude"));
                                busRoute.setLongitude(object.getString("longitude"));
                                busRoute.setDate(object.getString("dateCreated"));
                                busRoute.setPlaceWeight(object.getString("busRouteweight"));
                                busRoute.setPlaceId(object.getString("routename"));
                                arrayList.add(busRoute);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                        Collections.sort(arrayList, new Comparator<BusRoute>() {
                            @Override
                            public int compare(BusRoute o1, BusRoute o2) {
                                return o1.getDate().compareTo(o2.getDate());
                            }
                        });




                        boolean isBusLocationPassed = false;
                        for(int n = 0; n < arrayList.size(); n++)
                        {
                            try {

                                BusRoute object = arrayList.get(n);

                                param1 = Double.parseDouble(object.getLatitude());
                                param2 = Double.parseDouble(object.getLongitude());

                                latLng = new LatLng(param1, param2);
                                Geocoder geocoder = new Geocoder(MapsActivity.this, Locale.getDefault());
                                List<Address> addresses = null;
                                try {
                                    addresses = geocoder.getFromLocation(param1, param2, 1);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                String cityName = addresses.get(0).getAddressLine(0);
                                String stateName = addresses.get(0).getAddressLine(1);
                                String countryName = addresses.get(0).getAddressLine(2);
                                log.v("cityName", "" + cityName);
                                log.v("lat", "" + param1);
                                log.v("log", "" + param2);

                                BusRoute objectnext = null;
                                if( n < arrayList.size()-1 ) {
                                    objectnext = arrayList.get(n + 1);
                                }
                                if(object.getId().trim() .equals(jsonObjectData.getString("prevStop").trim())){

                                    Polyline line = mMap.addPolyline(new PolylineOptions()
                                            .add(new LatLng(Double.parseDouble(object.getLatitude()), Double.parseDouble(object.getLongitude())), new LatLng(jsonObjectData.getDouble("latitude"), jsonObjectData.getDouble("Longitude")))
                                            .width(5)
                                            .color(Color.GREEN));
                                    if( objectnext != null ) {
                                        Polyline line2 = mMap.addPolyline(new PolylineOptions()
                                                .add(new LatLng(jsonObjectData.getDouble("Lattitude"), jsonObjectData.getDouble("Longitude")), new LatLng(Double.parseDouble(objectnext.getLatitude()), Double.parseDouble(objectnext.getLongitude())))
                                                .width(5)
                                                .color(Color.parseColor("#C56E00")));
                                    }

                                    log.v("done", "1 " + jsonObjectData.getString("nextStop"));
                                    LatLng latLngCurrent = new LatLng(jsonObjectData.getDouble("Lattitude"), jsonObjectData.getDouble("Longitude"));
                                    mMap.addMarker(new MarkerOptions().position(latLngCurrent).title("" + cityName + "" + stateName + "" + countryName)
                                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.bus_blue)));
                                    mMap.addMarker(new MarkerOptions().position(latLng).title("" + cityName + "" + stateName + "" + countryName)
                                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.bus_green)));
                                    isBusLocationPassed = true;
                                }else if(isBusLocationPassed){
                                    if( objectnext != null ) {

                                        Polyline line = mMap.addPolyline(new PolylineOptions()
                                                .add(new LatLng(Double.parseDouble(object.getLatitude()), Double.parseDouble(object.getLongitude())), new LatLng(Double.parseDouble(objectnext.getLatitude()), Double.parseDouble(objectnext.getLongitude())))
                                                .width(5)
                                                .color(Color.parseColor("#C56E00")));
                                    }
                                    log.v("done", "2 " + jsonObjectData.getString("nextStop"));

                                    mMap.addMarker(new MarkerOptions().position(latLng).title("" + cityName + "" + stateName + "" + countryName)
                                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.bus_orange)));
                                }else{
                                    if( objectnext != null ) {

                                        Polyline line = mMap.addPolyline(new PolylineOptions()
                                                .add(new LatLng(Double.parseDouble(object.getLatitude()), Double.parseDouble(object.getLongitude())), new LatLng(Double.parseDouble(objectnext.getLatitude()), Double.parseDouble(objectnext.getLongitude())))
                                                .width(5)
                                                .color(Color.GREEN));
                                    }
                                    log.v("done", "3 " + jsonObjectData.getString("nextStop"));

                                    mMap.addMarker(new MarkerOptions().position(latLng).title("" + cityName + "" + stateName + "" + countryName)
                                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.bus_green)));

                                }

                                mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
                                mMap.animateCamera(CameraUpdateFactory.zoomTo(10.0f));



                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }

                        Toast.makeText(getApplicationContext(), "Location received, Latitude:" + param1 + " Longitude:" + param2, Toast.LENGTH_SHORT).show();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getApplicationContext(),"Error:"+error.getMessage(),Toast.LENGTH_SHORT).show();
            }
        });
        queue.add(stringRequest);    
    }       
}

任何帮助?

更新

我尝试使用solution onesolution two

在这两种情况下,我都收到错误:OVER_QUERY_LIMIT

任何人都有这方面的解决方案???

这就是我在android map中的方式..我想让它们在实际的道路上显示。

enter image description here

在网站上,它显示正确...

enter image description here

2 个答案:

答案 0 :(得分:2)

要在Android地图中显示实际道路路径,您可以使用下面给出的geodesic(true)

Polyline line = map.addPolyline(new PolylineOptions()
    .add(new LatLng(-37.81319, 144.96298), new LatLng(-31.95285, 115.85734))
    .width(25)
    .color(Color.BLUE)
    .geodesic(true));

根据此link(阅读测地线

  

测地线设置决定了线段之间的区段   绘制折线/多边形的连续顶点。短程   细分是那些遵循地球最短路径的细分   表面(球体),通常在地图上显示为带有曲线的曲线   墨卡托投影。非测地线段绘制为直线   在地图上。

     

通过调用在形状的选项对象上设置此属性   * Options.geodesic()其中true表示段应绘制为测地线,false表示段应绘制为   直线。如果未指定,则默认为非测地线段   (假)。

对于OVER_QUERY_LIMIT: - Google Maps APIs web services的使用受每24小时期间请求数量的特定限制。发送超过这些限制的请求将收到错误消息。

如果超出使用限制,您将获得OVER_QUERY_LIMIT状态代码作为回复。

这意味着Web服务将停止提供正常响应并切换到仅返回状态代码OVER_QUERY_LIMIT,直到再次允许更多使用。这可能发生:

  • 如果因为您的应用程序每秒发送的请求过多而收到错误,则会在几秒钟内完成。
  • 在接下来的24小时内,如果收到错误,因为您的应用程序每天发送的请求过多。每日配额将在太平洋时间午夜重置。

解决方案: -

通过结合两种方法可以解决上述问题:

  • 通过优化应用程序以更有效地使用Web服务来降低使用率。
  • 在可能的情况下,通过为您的Google Maps API for Work许可购买额外的限额来提高使用限制。

查看此link以获取详细信息。

希望这会对你有所帮助。

答案 1 :(得分:0)

错误

超出查询限制意味着您每秒向API执行的查询过多,或者您已超出配额。

为了进一步帮助您,我需要详细说明您正在使用哪些API,因为我不知道我假设您正在使用Google Maps Roads API,它会为您提供所需的路径。

使用限制

每个API都有使用限制。对于Roads API,您只能进行50次每秒查询(QPS),并且还有其他限制。要查看有关此API的限制列表,我建议您查看以下链接:

我没有使用Roads API!

如果您没有使用Roads API,则必须找到您正在使用的API及其限制。以下是Google地图提供的所有API列表:

好的,我知道我正在使用哪种API,而且我达到了极限。现在怎么办?

如果您已完成上述步骤,通常有两个主要选项可以避免达到限制:

  • 缓存信息
  • 限制请求

每个解决方案都是一个独立的世界,但我会给你一些关于这些概念的指示,这样你就可以更轻松地跟踪它们了:

我特别推荐最后一个链接,它指向官方文档,包括缓存和限制。

希望它有所帮助!

PS:我也提出了这个问题,没有找到真正的理由为什么有人会对它进行投票。不过我建议您添加Minimal Working Example而不是发布所有代码,这会让更多人愿意帮助您。

在Android案例中,我通常建议从头开始创建一个尽可能简约的项目,以便复制您的问题。