【问题标题】:moving map in mapview from one location to another in android将mapview中的地图从一个位置移动到android中的另一个位置
【发布时间】:2012-11-06 07:08:01
【问题描述】:

我的应用程序中有一种情况,我应该将我的地图从一个位置移动到另一个位置....我对 android 很陌生..我发现了如何在两个位置之间画一条线..

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

}

我被困在没有用户活动的情况下将地图从一个位置移动到另一个位置

例如:当应用程序启动显示纽约市的位置时,地图应移动到德克萨斯州......任何帮助将不胜感激

【问题讨论】:

    标签: android google-maps android-mapview android-maps


    【解决方案1】:

    试试这个类只传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;
    
                }
    
            }
        }
    

    【讨论】:

    • 这非常有用......但是在这个我可以得到路线......我想在没有用户帮助的情况下将地图移动到其他位置......
    • @aravindvarma : 然后在创建 pass lat,long in "setCenter" 时它会自动导航到你的位置。
    • 有两个地理点...我希望地图自动从一个位置导航到另一个位置..如果我通过“setCenter”,提供的位置将直接出现
    • @aravindvarma : 然后使用一些计时器,并在特定时间后调用该方法。
    • 谢谢你...我该怎么做才能让导航变慢...这样我才能看到地图移动
    【解决方案2】:

    如果您想将地图移动到特定位置,请尝试此操作,然后获取该位置的纬度或经度,然后传入以下内容:

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

    如果您想在两个位置之间绘制路径,那么只需在此传递 lat 和 lon:

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

    【讨论】:

    • 感谢您的回答..您代码中的意图必须在移动设备中打开浏览器或谷歌地图...我希望它发生在不使用浏览器或其他应用程序的应用程序中
    • @aravindvarma 我发布另一个绘制路径的答案试试。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多