本文介绍了任何人都可以指导我怎么去使用JSON两个位置之间的谷歌路线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听说KML文件不再可用,自2012年7月27日(因为谷歌已经改变了获取谷歌路线的结构,现在你只能得到它通过JSON和XML)所以PLZ指导我如何使在2位置行进路线。

跌破code是工作的罚款NW享受GUYS这是我的code:

我refered此链接:PlacesMapActivity.java

在低于code它显示2点之间的直线。

 公共类PlacesMapActivity扩展MapActivity {
@覆盖
公共无效的onCreate(包savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.map_places);
意图I = getIntent(); //获取意图数据
字符串user_latitude = i.getStringExtra(user_latitude); //用户当前的地理位置
字符串user_longitude = i.getStringExtra(user_longitude); // Userscurrent的地理位置
nearPlaces =(PlacesList)i.getSerializableExtra(near_places); // Nearplaces列表
图形页面=(图形页面)findViewById(R.id.mapView);
mapView.setBuiltInZoomControls(真正的);
mapOverlays =调用MapView.getOverlays();
的GeoPoint =新的GeoPoint((int)的(Double.parseDouble(user_latitude)* 1E6),(int)的(Double.parseDouble(user_longitude)* 1E6)); //的GeoPoint放置在地图上的
geoPoint1 =新的GeoPoint((INT)(Double.parseDouble(12.930621)* 1E6)
            (中间体)(Double.parseDouble(77.581710)* 1E6)); //的GeoPoint到Clientplace于地图
可绘制drawable_user = this.getResources()
    .getDrawable(R.drawable.mark_red); //绘制对象标记图标
可绘制drawable_client = this.getResources()
    .getDrawable(R.drawable.mark_blue); //绘制对象客户端图标
可绘制绘制= this.getResources()
    .getDrawable(R.drawable.clientflag); //绘制对象标记图标
//地图覆盖项目
itemizedOverlay =新AddItemizedOverlay(drawable_user,这一点);
overlayitem =新OverlayItem(GeoPoint对象,你的位置,那就是你!);
itemizedOverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedOverlay);
itemizedOverlay.populateNow();
//地图客户端覆盖项目
itemizedOverlay1 =新AddItemizedOverlay(drawable_client,这一点);
overlayitem1 =新OverlayItem(geoPoint1,你LOCATION2,我是乌拉圭回合的客户!);
itemizedOverlay1.addOverlay(overlayitem1);
mapOverlays.add(itemizedOverlay1);
itemizedOverlay1.populateNow();
//地图客户端覆盖项目
itemizedOverlay =新AddItemizedOverlay(绘制,这一点);
MC = mapView.getController();


//这些值用于地图边界区域获得
//在这里你可以看到所有在屏幕上的标记区域
INT minLat = Integer.MAX_VALUE的;
INT闽龙= Integer.MAX_VALUE的;
INT maxLat = Integer.MIN_VALUE的;
INT MAXLONG = Integer.MIN_VALUE的;

//检查空的情况下,它是空
如果(nearPlaces.results!= NULL){
//通过所有的地方环
对于(地方的地方:nearPlaces.results){
纬度= place.geometry.location.lat; // 纬度
经度= place.geometry.location.lng; // 经度
// GeoPoint对象放置在地图上
geoPoin =新的GeoPoint((INT)(纬度* 1E6)
    (中间体)(经度* 1E6));
//地图覆盖项目
overlayitem =新OverlayItem(geoPoin,place.name,
    place.vicinity);
itemizedOverlay.addOverlay(overlayitem);
//计算地图边界区域
minLat =(int)的Math.min(geoPoin.getLatitudeE6(),minLat);
闽龙=(INT)Math.min(geoPoin.getLongitudeE6(),闽龙);
maxLat =(int)的Math.max(geoPoin.getLatitudeE6(),maxLat);
MAXLONG =(INT)Math.max(geoPoin.getLongitudeE6(),MAXLONG);
}
mapOverlays.add(itemizedOverlay);

//显示所有的覆盖件
itemizedOverlay.populateNow();
}
//调整缩放比例,以便您可以看到所有在地图上的标记
。mapView.getController()zoomToSpan(Math.abs(minLat  -  maxLat),Math.abs(闽龙 -  MAXLONG));
//显示在地图的中心
mc.animateTo(新的GeoPoint((maxLat + minLat)/ 2,(MAXLONG +闽龙)/ 2));
mc.animateTo(geoPoint1);
//mapView.postInvalidate();
myoverlay =新MyOverlay();
mapOverlays.add(myoverlay);
}
@覆盖
公共布尔onCreateOptionsMenu(菜单菜单)
{
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.activity_main,菜单);
返回true;
}
/ **
*事件处理个人菜单项目中选择
*确定一个菜单项通过它的id
* * /
@覆盖
公共布尔onOptionsItemSelected(菜单项项)
{
开关(item.getItemId())
{
案例R.id.mylocation:
//单菜单项被选中做一些事情
Toast.makeText(PlacesMapActivity.this,移动到当前位置,Toast.LENGTH_SHORT).show();
// geoPoint.gpsCurrentLocation();
 返回true;
案例R.id.mapStreet:
Toast.makeText(PlacesMapActivity.this,普通地图街景视图,Toast.LENGTH_SHORT).show();
如果(mapView.isSatellite()==真){
mapView.setSatellite(假);
}
返回true;
案例R.id.mapSatellite:
Toast.makeText(PlacesMapActivity.this,地图卫星视图,Toast.LENGTH_SHORT).show();
如果(mapView.isSatellite()== FALSE){
mapView.setSatellite(真正的);
}
返回true;
默认:
返回super.onOptionsItemSelected(项目);
}
}
@覆盖
保护的布尔isRouteDisplayed(){
返回false;
}

添加此道航
私人无效DrawPath(的GeoPoint scrgeoPoint,的GeoPoint destgeoPoint,GeoPoint对象destgeopointsearch,诠释绿色,图形页面mMapView){
     HttpClient的HttpClient的=新DefaultHttpClient();
        HttpPost httppost =新HttpPost(makeUrl(scrgeoPoint,destgeoPoint,destgeopointsearch));
        HTT presponse响应;
        尝试 {
            响应= httpclient.execute(httppost);

            HttpEntity实体= response.getEntity();
            InputStream的是= NULL;

            是= entity.getContent();
            的BufferedReader读卡器=新的BufferedReader(新的InputStreamReader(
                    是,ISO-8859-1),8);
            StringBuilder的SB =新的StringBuilder();
            sb.append(reader.readLine()+\ N);
            串行=0;
            而((行= reader.readLine())!= NULL){
                sb.append(行+\ N);
            }
            is.close();
            reader.close();
            字符串结果= sb.toString();
            的JSONObject的JSONObject =新的JSONObject的(结果);
            JSONArray routeArray = jsonObject.getJSONArray(路);
            的JSONObject路由= routeArray.getJSONObject(0);
            JSONObject的overviewPolylines = routes.getJSONObject(overview_polyline);
            字符串连接codedString = overviewPolylines.getString(分);
            名单<的GeoPoint> pointToDraw =去$ C $℃聚(EN codedString);
            。mMapView.getOverlays()增加(新MyOverLay(pointToDraw));
        }赶上(ClientProtocolException E){
            e.printStackTrace();
        }赶上(IOException异常E){
            e.printStackTrace();
        }赶上(例外五){
            e.printStackTrace();
        }
    }

私人列表<的GeoPoint>德$ C $℃聚(字符串连接codeD){
     名单<的GeoPoint>聚=新的ArrayList<的GeoPoint>();
        INT指数= 0,len个= EN coded.length();
        INT纬度= 0,LNG = 0;

        而(指数< LEN){
            INT B,移= 0,结果为0;
            做 {
                B = EN coded.charAt(指数++) -  63;
                结果| =(B和0x1F的)LT;<转移;
                Shift + = 5;
            }而(B> = 0x20的);
            INT DLAT =((导致&安培; 1)= 0〜(结果>→1):!?(导致>→1));
            纬度+ = DLAT;

            移= 0;
            结果= 0;
            做 {
                B = EN coded.charAt(指数++) -  63;
                结果| =(B和0x1F的)LT;<转移;
                Shift + = 5;
            }而(B> = 0x20的);
            INT dlng =((导致&安培; 1)= 0〜(结果>→1):!?(导致>→1));
            LNG + = dlng;

            的GeoPoint P =新的GeoPoint((INT)(((双)纬度/ 1E5)* 1E6)
                    (INT)(((双)LNG / 1E5)* 1E6));
            poly.add(对);
        }
        返回聚;
    }

私人字符串makeUrl(的GeoPoint scrgeoPoint,的GeoPoint destgeoPoint,GeoPoint对象destgeopointsearch){
    StringBuilder的urlString =新的StringBuilder();

    urlString.append(http://maps.googleapis.com/maps/api/directions/json);
    urlString.append(原产地=?); //从
    urlString.append(Double.toString((双)scrgeoPoint.getLatitudeE6()/ 1.0E6));
    urlString.append(,);
    urlString.append(Double.toString((双)scrgeoPoint.getLongitudeE6()/ 1.0E6));

    urlString.append(&放大器;目标=); //给
    urlString.append(Double.toString((双)destgeoPoint.getLatitudeE6()/ 1.0E6));
    urlString.append(,);
    urlString.append(Double.toString((双)destgeoPoint.getLongitudeE6()/ 1.0E6));

   / * urlString.append(&放大器;目标=); //搜索以
    urlString.append(Double.toString((双)destgeopointsearch.getLatitudeE6()/ 1.0E6));
    urlString.append(,);
    urlString.append(Double.toString((双)destgeopointsearch.getLongitudeE6()/ 1.0E6));
    * /
    urlString.append(&放大器,传感器=假);

    Log.d(XXX,URL =+ urlString.toString());
    返回urlString.toString();
}
 

最后,我有两个点之间的行进路线图。增加这code。

 类MyOverLay扩展覆盖{
私人诠释pathColor;
私人最终名单,其中,GeoPoint对象>分;
私人布尔drawStartEnd;

公共MyOverLay(名单<的GeoPoint> pointToDraw){
    这个(pointToDraw,Color.MAGENTA,真正的);
}

公共MyOverLay(名单<的GeoPoint>点,INT pathColor,布尔drawStartEnd){
    this.points =分;
    this.pathColor = pathColor;
    this.drawStartEnd = drawStartEnd;
}

私人无效drawOval(画布油画,漆漆,点对点){
    油漆ovalPaint =新的油漆(涂料);
    ovalPaint.setStyle(Paint.Style.FILL_AND_STROKE);
    ovalPaint.setStrokeWidth(2);
    ovalPaint.setColor(Color.BLUE);
    INT _radius = 6;
    RectF椭圆形=新RectF(point.x  -  _radius,point.y  -  _radius,
            point.x + _radius,point.y + _radius);
    canvas.drawOval(椭圆形,ovalPaint);
}

公共布尔平局(画布油画,图形页面图形页面,布尔阴影,
        时长){
    投影投影= MapView.getProjection()在;
    如果(影子==假放;&放大器;点!= NULL){
        点的startPoint = NULL,终端= NULL;
        路径path =新路径();
        //我们正在创造的路径
的for(int i = 0; I< points.size();我++){
的GeoPoint gPointA = points.get(ⅰ);
点pointA =新的点();
projection.toPixels(gPointA,pointA);
如果(ⅰ== 0){//这是起点
的startPoint = pointA;
path.moveTo(pointA.x,pointA.y);
} 其他 {
如果(ⅰ== points.size() -  1)//这是结束点
                终点= pointA;
            path.lineTo(pointA.x,pointA.y);
        }
    }

    涂料粉刷=新的油漆();
    paint.setAntiAlias​​(真正的);
    paint.setColor(pathColor);
    paint.setStyle(Paint.Style.STROKE);
    paint.setStrokeWidth(5);
    paint.setAlpha(90);
    如果(getDrawStartEnd()){
        如果(的startPoint!= NULL){
            drawOval(画布,颜料,的startPoint);
        }
        如果(端点!= NULL){
            drawOval(画布,颜料,终点);
        }
    }
    如果(!path.isEmpty())
        canvas.drawPath(路径,油漆);
}
返回super.draw(帆布,图形页面,阴影,时);
}

公共布尔getDrawStartEnd(){
返回drawStartEnd;
}

公共无效setDrawStartEnd(布尔markStartEnd){
drawStartEnd = markStartEnd;
}
}
}
 

解决方案

您可以在这里,提供完整的答案看我的帖子如何做到这一点的JSON,因为谷歌关闭KML。

I have heard that KML file is no longer available since 27 July 2012 (because Google has changed the structure of retrieving Google Directions, now you can only get it by JSON or XML)So plz guide me how to make road route between 2 location.

BELOW CODE IS WORKING FINE NW ENJOY GUYSThis is my code:

I refered this link : http://www.androidhive.info/2012/08/android-working-with-google-places-and-maps-tutorial/PlacesMapActivity.java

In below code it is showing straight line between 2 point.

public class PlacesMapActivity extends MapActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_places);
Intent i = getIntent(); // Getting intent data  
String user_latitude = i.getStringExtra("user_latitude");// Users current geo location
String user_longitude = i.getStringExtra("user_longitude");//Userscurrent geo location      
nearPlaces = (PlacesList) i.getSerializableExtra("near_places");// Nearplaces list
mapView = (MapView) findViewById(R.id.mapView);
mapView.setBuiltInZoomControls(true);
mapOverlays = mapView.getOverlays();
geoPoint = new GeoPoint((int) (Double.parseDouble(user_latitude) * 1E6),                              (int) (Double.parseDouble(user_longitude) * 1E6));// Geopoint to place on map
geoPoint1 = new GeoPoint((int) (Double.parseDouble("12.930621") * 1E6),
            (int) (Double.parseDouble("77.581710") * 1E6));//Geopoint to Clientplace on map     
Drawable drawable_user = this.getResources()
    .getDrawable(R.drawable.mark_red);      // Drawable marker icon     
Drawable drawable_client = this.getResources() 
    .getDrawable(R.drawable.mark_blue);     // Drawable Client icon 
Drawable drawable = this.getResources()
    .getDrawable(R.drawable.clientflag);    // Drawable marker icon
// Map overlay item
itemizedOverlay = new AddItemizedOverlay(drawable_user, this);
overlayitem = new OverlayItem(geoPoint, "Your Location","That is you!");
itemizedOverlay.addOverlay(overlayitem);        
mapOverlays.add(itemizedOverlay);
itemizedOverlay.populateNow();      
// Map client overlay item
itemizedOverlay1 = new AddItemizedOverlay(drawable_client, this);       
overlayitem1 = new OverlayItem(geoPoint1, "Your Location2", "I am ur client!");
itemizedOverlay1.addOverlay(overlayitem1);              
mapOverlays.add(itemizedOverlay1);
itemizedOverlay1.populateNow();
// Map client overlay item  
itemizedOverlay = new AddItemizedOverlay(drawable, this);
mc = mapView.getController();


// These values are used to get map boundary area
// The area where you can see all the markers on screen
int minLat = Integer.MAX_VALUE;
int minLong = Integer.MAX_VALUE;
int maxLat = Integer.MIN_VALUE;
int maxLong = Integer.MIN_VALUE;

// check for null in case it is null
if (nearPlaces.results != null) {
// loop through all the places
for (Place place : nearPlaces.results) {
latitude = place.geometry.location.lat; // latitude
longitude = place.geometry.location.lng; // longitude
// Geopoint to place on map
geoPoin = new GeoPoint((int) (latitude * 1E6),
    (int) (longitude * 1E6));
// Map overlay item
overlayitem = new OverlayItem(geoPoin, place.name,
    place.vicinity);
itemizedOverlay.addOverlay(overlayitem);
// calculating map boundary area
minLat  = (int) Math.min( geoPoin.getLatitudeE6(), minLat );
minLong = (int) Math.min( geoPoin.getLongitudeE6(), minLong);
maxLat  = (int) Math.max( geoPoin.getLatitudeE6(), maxLat );
maxLong = (int) Math.max( geoPoin.getLongitudeE6(), maxLong );
}
mapOverlays.add(itemizedOverlay);

// showing all overlay items
itemizedOverlay.populateNow();
}
// Adjusting the zoom level so that you can see all the markers on map
mapView.getController().zoomToSpan(Math.abs( minLat - maxLat ), Math.abs( minLong -     maxLong ));
// Showing the center of the map
mc.animateTo(new GeoPoint((maxLat + minLat)/2, (maxLong + minLong)/2 ));
mc.animateTo(geoPoint1);
//mapView.postInvalidate();
myoverlay = new MyOverlay();
mapOverlays.add(myoverlay); 
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.activity_main, menu);
return true;
}
/**
* Event Handling for Individual menu item selected
* Identify single menu item by it's id
* */
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.mylocation:
// Single menu item is selected do something
Toast.makeText(PlacesMapActivity.this, "Moving To Current location",      Toast.LENGTH_SHORT).show();
// geoPoint.gpsCurrentLocation();
 return true;
case R.id.mapStreet:
Toast.makeText(PlacesMapActivity.this, "Map Normal Street View",   Toast.LENGTH_SHORT).show();
if(mapView.isSatellite()==true){
mapView.setSatellite(false);
}
return true;
case R.id.mapSatellite:
Toast.makeText(PlacesMapActivity.this, "Map Satellite View",  Toast.LENGTH_SHORT).show();
if(mapView.isSatellite()==false){
mapView.setSatellite(true);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}        
@Override
protected boolean isRouteDisplayed() {
return false;
}

add this road route
private void DrawPath(GeoPoint scrgeoPoint, GeoPoint destgeoPoint, GeoPoint destgeopointsearch, int green, MapView mMapView) {
     HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(makeUrl(scrgeoPoint, destgeoPoint, destgeopointsearch));
        HttpResponse response;
        try {
            response = httpclient.execute(httppost);

            HttpEntity entity = response.getEntity();
            InputStream is = null;

            is = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            sb.append(reader.readLine() + "\n");
            String line = "0";
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            reader.close();
            String result = sb.toString();
            JSONObject jsonObject = new JSONObject(result);
            JSONArray routeArray = jsonObject.getJSONArray("routes");
            JSONObject routes = routeArray.getJSONObject(0);
            JSONObject overviewPolylines = routes.getJSONObject("overview_polyline");
            String encodedString = overviewPolylines.getString("points");
            List<GeoPoint> pointToDraw = decodePoly(encodedString);
            mMapView.getOverlays().add(new MyOverLay(pointToDraw));
        } catch (ClientProtocolException e) {            
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

private List<GeoPoint> decodePoly(String encoded) {
     List<GeoPoint> poly = new ArrayList<GeoPoint>();
        int index = 0, len = encoded.length();
        int lat = 0, lng = 0;

        while (index < len) {
            int b, shift = 0, result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lat += dlat;

            shift = 0;
            result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lng += dlng;

            GeoPoint p = new GeoPoint((int) (((double) lat / 1E5) * 1E6),
                    (int) (((double) lng / 1E5) * 1E6));
            poly.add(p);
        }
        return poly;
    }

private String makeUrl(GeoPoint scrgeoPoint, GeoPoint destgeoPoint, GeoPoint destgeopointsearch) {
    StringBuilder urlString = new StringBuilder();

    urlString.append("http://maps.googleapis.com/maps/api/directions/json");
    urlString.append("?origin=");// from
    urlString.append(Double.toString((double) scrgeoPoint.getLatitudeE6() / 1.0E6));
    urlString.append(",");
    urlString.append(Double.toString((double) scrgeoPoint.getLongitudeE6() / 1.0E6));

    urlString.append("&destination=");// to
    urlString.append(Double.toString((double) destgeoPoint.getLatitudeE6() / 1.0E6));
    urlString.append(",");
    urlString.append(Double.toString((double) destgeoPoint.getLongitudeE6() / 1.0E6));

   /* urlString.append("&destination=");// searchto
    urlString.append(Double.toString((double) destgeopointsearch.getLatitudeE6() / 1.0E6));
    urlString.append(",");
    urlString.append(Double.toString((double) destgeopointsearch.getLongitudeE6() / 1.0E6));
    */
    urlString.append("&sensor=false");

    Log.d("xxx", "URL=" + urlString.toString());
    return urlString.toString();
}

At Last i got road route map between two point.. Add this code.

class MyOverLay extends Overlay {
private int pathColor;
private final List<GeoPoint> points;
private boolean drawStartEnd;

public MyOverLay(List<GeoPoint> pointToDraw) {         
    this(pointToDraw, Color.MAGENTA, true);
}

public MyOverLay(List<GeoPoint> points, int pathColor, boolean drawStartEnd) {
    this.points = points;
    this.pathColor = pathColor;
    this.drawStartEnd = drawStartEnd;
}

private void drawOval(Canvas canvas, Paint paint, Point point) {
    Paint ovalPaint = new Paint(paint);
    ovalPaint.setStyle(Paint.Style.FILL_AND_STROKE);
    ovalPaint.setStrokeWidth(2);
    ovalPaint.setColor(Color.BLUE);
    int _radius = 6;
    RectF oval = new RectF(point.x - _radius, point.y - _radius,
            point.x + _radius, point.y + _radius);
    canvas.drawOval(oval, ovalPaint);
}

public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
        long when) {
    Projection projection = mapView.getProjection();
    if (shadow == false && points != null) {
        Point startPoint = null, endPoint = null;
        Path path = new Path();
        // We are creating the path
for (int i = 0; i < points.size(); i++) {
GeoPoint gPointA = points.get(i);
Point pointA = new Point();
projection.toPixels(gPointA, pointA);
if (i == 0) { // This is the start point
startPoint = pointA;
path.moveTo(pointA.x, pointA.y);
} else {
if (i == points.size() - 1)// This is the end point
                endPoint = pointA;
            path.lineTo(pointA.x, pointA.y);
        }
    }

    Paint paint = new Paint();
    paint.setAntiAlias(true);
    paint.setColor(pathColor);
    paint.setStyle(Paint.Style.STROKE);
    paint.setStrokeWidth(5);
    paint.setAlpha(90);
    if (getDrawStartEnd()) {
        if (startPoint != null) {
            drawOval(canvas, paint, startPoint);
        }
        if (endPoint != null) {
            drawOval(canvas, paint, endPoint);
        }
    }
    if (!path.isEmpty())
        canvas.drawPath(path, paint);
}
return super.draw(canvas, mapView, shadow, when);
}

public boolean getDrawStartEnd() {
return drawStartEnd;
}

public void setDrawStartEnd(boolean markStartEnd) {
drawStartEnd = markStartEnd;
}
}
}
解决方案

You can see my post here with full answer on how to do it in JSON since Google shut down KML.

这篇关于任何人都可以指导我怎么去使用JSON两个位置之间的谷歌路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 08:15