moving map in mapview from one location to another in android

别等时光非礼了梦想. 提交于 2019-12-24 20:17:00

问题


i have a situation in my app where i should move my map from one location to another location....i am quite new to android..and i found out how to draw a line in between two locations..

public class Mapview extends MapActivity implements LocationListener{
MapController mc;
GeoPoint p,p1,p2;
LocationManager lm;
String provider;
 class Mapoverlay extends com.google.android.maps.Overlay
 {

    @Override
    public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
            long when) {
        // TODO Auto-generated method stub
        super.draw(canvas, mapView, shadow);
        Point screenpoints=new Point();     
        Point screenpoints1=new Point();
        Point screenpoints2=new Point();
         Paint paint;
         paint = new Paint();
         paint.setColor(Color.RED);
         paint.setAntiAlias(true);
         paint.setStyle(Style.FILL);
         paint.setStrokeWidth(2);
         paint.setAlpha(120);
         Paint paint1;
         paint1 = new Paint();
         paint1.setColor(Color.BLUE);
         paint1.setAntiAlias(true);
         paint1.setStyle(Style.FILL);
         paint1.setStrokeWidth(2);
         paint1.setAlpha(120);
        if(p != null)
        {
            mapView.getProjection().toPixels(p, screenpoints);
            mapView.getProjection().toPixels(p1, screenpoints1);
            mapView.getProjection().toPixels(p2, screenpoints2);
//              Bitmap map=BitmapFactory.decodeResource(getResources(),      R.drawable.pushpin1);
//               canvas.drawBitmap(map, screenpoints.x, screenpoints.y-53, null);
             canvas.drawLine(screenpoints.x,screenpoints.y,screenpoints1.x,screenpoints1.y, paint);
             canvas.drawLine(screenpoints.x,screenpoints.y,screenpoints2.x,screenpoints2.y, paint);
        }

        return true;

    }

 }

@Override
protected void onCreate(Bundle icicle) {
    // TODO Auto-generated method stub
    super.onCreate(icicle);
    setContentView(R.layout.mapview);
    MapView map=(MapView)findViewById(R.id.mapView);
    map.setBuiltInZoomControls(true);
     mc=map.getController();
     String[] coordinates={"51.4750766129036", "-3.15672342166522"};
     double lat = Double.parseDouble(coordinates[0]);
     double lng = Double.parseDouble(coordinates[1]);

     p=new GeoPoint((int)(lat*1E6), (int)(lng*1E6));
     String[] coordinates1={"17.453117" , "78.467586" };
     double lat1 = Double.parseDouble(coordinates1[0]);
     double lng1 = Double.parseDouble(coordinates1[1]);

     p2=new GeoPoint((int)(lat1*1E6), (int)(lng1*1E6));
      p1 = new GeoPoint(19240000,-99120000);

//        p = new GeoPoint(19241000,-99121000);
     lm=(LocationManager)getSystemService(Context.LOCATION_SERVICE);

     Criteria criteria = new Criteria();
     criteria.setAccuracy(Criteria.ACCURACY_FINE);
     criteria.setAltitudeRequired(false);
     criteria.setBearingRequired(false);
     criteria.setCostAllowed(true);
     criteria.setPowerRequirement(Criteria.POWER_LOW);
     provider=lm.getBestProvider(criteria, true);


     Location loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
     List<String>  lists=lm.getAllProviders();
//       float f=loc.distanceTo(loc);
     if (loc!=null){
         System.out.println("Provider " + provider + " has been selected.");
        onLocationChanged(loc); 
     }else{
         Toast.makeText(getApplicationContext(), "Provider " + provider+ loc +  lists+" has not been selected.", 5000).show();
//           this.finish();
     }

//       Toast.makeText(getApplicationContext(), p.getLatitudeE6()+p.getLongitudeE6(), Toast.LENGTH_SHORT).show();
     mc.animateTo(p);
     mc.setZoom(1);
     map.invalidate();
     Mapoverlay mapOverlay = new Mapoverlay();
        List<Overlay> listOfOverlays = map.getOverlays();
        listOfOverlays.clear();
        listOfOverlays.add(mapOverlay);        

}

i am stuck at moving map from one location to another without user activity

for example:when the app initiates location of newyork city is shown then the map should move to texas ...any help willl be grateful


回答1:


Try This class just pass Activity act,GeoPoint src,GeoPoint dest, int color, MapView mMapView

To call this class do this

    new getRoute().DrawPath(this,mGeoPoint,getGeoPoint,Color.RED,mMapView);  





  public class getRoute 
    {
        /*Variable*/
        double mIntentLatitude, mIntentLongitude;
        double mCursorLatitude, mCursorLongitude, mStartLatitude, mStartLongitude, mEndLatitude, MEndLongitude;
        String mJsonData;
        String mEnd_Address, mStart_Address, mName;
        int mLength;
        GeoPoint mGeoPoint = new GeoPoint(220328269, 725588202);
        double mLatitude_End[], mLongitude_End[], mLatitude_Start[], mLongitude_Start[];
        Activity activity;


        public getRoute
        (){

        }   
        boolean error = false;
        public void DrawPath(Activity act,GeoPoint src,GeoPoint dest, int color, MapView mMapView01)
        {
            // connect to map web service
            DrawPathBack draw = new DrawPathBack(act, src, dest, color, mMapView01);
            draw.execute("Draw");
        }
        public class DrawPathBack extends AsyncTask<String, Integer,Void>
        {
            ProgressDialog bar;
            List<Overlay> mListOverlay;
            MapOverlay mapOverlay;
            ItemizedOverlay<OverlayItem> mItemizedOverlay;

            GeoPoint src,dest;
            int color;
            MapView mMapView;
            CommonMethod mCommonMethod;
            String [] pairs;
            String[] lngLat;



            public DrawPathBack(Activity act,GeoPoint gpsrc,GeoPoint gpdest, int c, MapView mMap)
            {
                activity =act;
                src=gpsrc;
                dest=gpdest;
                color = c;
                mMapView=mMap;
                mListOverlay = mMapView.getOverlays();
                mapOverlay = new MapOverlay(mGeoPoint);
                mListOverlay.add(mapOverlay);
                mMapView.invalidate();

            }
            @Override
            protected Void doInBackground(String... params)
            {



                HttpParams httpParameters = new BasicHttpParams();

                HttpConnectionParams.setSoTimeout(httpParameters, 60000);

                HttpClient client = new DefaultHttpClient();

                try {

                    HttpPost httpPost = new HttpPost("http://maps.googleapis.com/maps/api/directions/json?origin="+ (Double.toString((double)src.getLatitudeE6()/1.0E6)) + "," +(Double.toString((double)src.getLongitudeE6()/1.0E6 ) + "&destination=" + (Double.toString((double)dest.getLatitudeE6()/1.0E6)) + ","+  (Double.toString((double)dest.getLongitudeE6()/1.0E6))+ "&sensor=false"));
                    mIntentLatitude=((double)src.getLatitudeE6()/1.0E6);
                    mIntentLongitude=((double)src.getLongitudeE6()/1.0E6);

                    //httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    HttpResponse httpResponse = client.execute(httpPost);
                    mJsonData = EntityUtils.toString(httpResponse.getEntity());

                } catch (ClientProtocolException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return null;
            }
            @Override
            protected void onProgressUpdate(Integer... progress)
            {
                bar.setMessage("Time Progress "+progress[0]);
            }
            @Override
            protected void onPostExecute(Void result) 
            {
                try {

                    JSONObject jsonObj = new JSONObject(mJsonData);

                    // grabbing the routes object
                    JSONArray routes = jsonObj.getJSONArray("routes");

                    for (int i = 0; i < routes.length(); i++) {

                        JSONObject rout = routes.getJSONObject(i);

                        JSONObject bounds = rout.getJSONObject("bounds");

                        JSONObject northest = bounds.getJSONObject("northeast");

                        mStartLatitude = northest.getDouble("lat");
                        mStartLongitude = northest.getDouble("lng");

                        JSONObject southwest = bounds.getJSONObject("southwest");
                        mEndLatitude = southwest.getDouble("lat");
                        MEndLongitude = southwest.getDouble("lng");
                        System.out.println("get data from jeson" + mCursorLatitude + mCursorLongitude + mEndLatitude
                                + MEndLongitude);

                        // grabbing the routes legs
                        JSONArray legs = rout.getJSONArray("legs");
                        System.out.println("length of legs array     " + legs.length());
                        for (int j = 0; j < legs.length(); j++) {
                            JSONObject leg = legs.getJSONObject(j);
                            System.out.println("enter in second array");

                            JSONObject distance = leg.getJSONObject("distance");
                            String mTextDistent = distance.getString("text");
                            System.out.println("distances bitween two point" + mTextDistent);
                            JSONObject duration = leg.getJSONObject("duration");
                            String mTextDurestion = duration.getString("text");

                            mEnd_Address = leg.getString("end_address");

                            mStart_Address = leg.getString("start_address");
                            System.out.println("get data from jeson in second arry"
                                    + mTextDurestion + " " + mEnd_Address + "  " + mStart_Address);

                            JSONArray step = leg.getJSONArray("steps");

                            mLength = step.length();

                            mLatitude_End = new double[mLength];
                            mLongitude_End = new double[mLength];
                            mLatitude_Start = new double[mLength];
                            mLongitude_Start = new double[mLength];

                            for (int k = 0; k < step.length(); k++) {

                                JSONObject st = step.getJSONObject(k);

                                System.out.println("enter in third array");
                                JSONObject end_lo = st.getJSONObject("end_location");

                                JSONObject start_lo = st
                                .getJSONObject("start_location");

                                mLatitude_End[k] = end_lo.getDouble("lat");
                                mLongitude_End[k] = end_lo.getDouble("lng");

                                mLatitude_Start[k] = start_lo.getDouble("lat");
                                mLongitude_Start[k] = start_lo.getDouble("lng");

                            }
                            for (int mDistanse = 0; mDistanse < mLength; mDistanse++) {
                                System.out.println("end location let" + mLatitude_End[mDistanse]);
                                System.out.println("end location long+"
                                        + mLongitude_End[mDistanse]);
                                System.out.println("Start location let"
                                        + mLatitude_Start[mDistanse]);
                                System.out.println("Start location long"
                                        + mLongitude_Start[mDistanse]);
                            }
                        }
                    }

                } catch (Exception e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }
            }
        }

        public class MapOverlay extends com.google.android.maps.Overlay {

            public MapOverlay(GeoPoint mGeoPoint) {

            }

            @Override
            public boolean draw(final Canvas canvas, MapView mapView,
                    boolean shadow, long when) {

                Point mpoint = new Point();
                Point mpoint1 = new Point();

                int let[] = new int[mLength];
                int lon[] = new int[mLength];
                int let_end[] = new int[mLength];
                int lon_end[] = new int[mLength];
                GeoPoint newGeoPoint = null;
                GeoPoint newGeoPoint1;
                for (int k = 0; k < mLength; k++) {

                    let[k] = (int) (mLatitude_Start[k] * 1E6);
                    lon[k] = (int) (mLongitude_Start[k] * 1E6);

                    let_end[k] = (int) (mLatitude_End[k] * 1E6);
                    lon_end[k] = (int) (mLongitude_End[k] * 1E6);
                    newGeoPoint1 = new GeoPoint(let_end[k], lon_end[k]);
                    newGeoPoint = new GeoPoint(let[k], lon[k]);
                    mapView.getProjection().toPixels(newGeoPoint, mpoint);
                    mapView.getProjection().toPixels(newGeoPoint1, mpoint1);
                    Paint paint = new Paint();

                    paint.setColor(Color.RED);
                    paint.setStyle(Paint.Style.FILL_AND_STROKE);
                    paint.setStrokeWidth(5);
                    canvas.drawCircle(mpoint.x, mpoint.y, 5, paint);
                    paint.setColor(Color.BLUE);
                    canvas.drawLine(mpoint.x, mpoint.y, mpoint1.x, mpoint1.y, paint);
                    paint.setColor(Color.BLACK);
                    paint.setStrokeWidth(100);
                    paint.setStyle(Paint.Style.FILL);
                    if(k==mLength-1){
                        Bitmap bmp = BitmapFactory.decodeResource(activity.getResources(), R.drawable.green_pin);
                        canvas.drawBitmap(bmp,mpoint1.x ,mpoint1.y-30, null);
                    }
                    GeoPoint dumy=new GeoPoint((int)(mIntentLatitude * 1E6), (int)(mIntentLongitude * 1E6));
                    Point dumy1 = new Point();
                    mapView.getProjection().toPixels(dumy, dumy1);
                    Bitmap bmp = BitmapFactory.decodeResource(activity.getResources(), R.drawable.dest_pin);
                    canvas.drawBitmap(bmp,dumy1.x,dumy1.y - 25, null);
                    mapView.getController().animateTo(dumy);
                    mapView.invalidate();
                }
                return false;

            }

        }
    }



回答2:


Try this if you want to move map on particular position then get lat or long of that position and just pass in this :

MapController mMapController;

mMapController=mMapView.getController();
    mMapController.setCenter(new GeoPoint((int)(lat * 1E6), (int)(lon * 1E6)));

and if you want to draw path between two location then just pass lat and lon in this :

Intent intent = new Intent(android.content.Intent.ACTION_VIEW, 
                Uri.parse("http://maps.google.com/maps?saddr="+ String.valueOf(from_lattitude) +","+ String.valueOf(from_longitude) +"&daddr="+ String.valueOf(dest_lati) +","+ String.valueOf(dest_longi)));
                startActivity(intent);


来源:https://stackoverflow.com/questions/13246084/moving-map-in-mapview-from-one-location-to-another-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!