在两个坐标之间绘制路线

我正在使用Google的Google Maps Directions api,并且试图在2个坐标之间插入一条折线,该怎么做?

我已经在 gradle.properties 中添加了API密钥,如下所示:

  

GOOGLE_MAPS_API_KEY = MY-API-KEY-HERE

我可以在代码内访问“ LatLng”等,因此一切似乎都正常。

但是我的问题是..如何在一条路线的坐标之间绘制一条折线?我已经检查了其他一些示例,但似乎都没有用。我是否必须从网上获取数据,或者是否已经设置好所有内容?

public class Mapsactivity extends Fragmentactivity implements OnmapReadyCallback{

private GoogleMap mMap;
MarkerOptions place1,place2;

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

    getaddressDirection();
}

public void getaddressDirection(){
    place1 = new MarkerOptions().position(new LatLng(57.6800907,12.0031394)).title("Loc1");
    place2 = new MarkerOptions().position(new LatLng(57.9576648,12.1188331)).title("Loc2");
}


@Override
public void onmapReady(GoogleMap googleMap) {
    mMap = googleMap;

    // Add a marker in Sydney and move the camera
    mMap.setMyLocationEnabled(true);

    //Adding marker between two coordinates
    mMap.addMarker(place1);
    mMap.addMarker(place2);
}

}

caosh666666 回答:在两个坐标之间绘制路线

您需要在地图上添加折线和多边形。

  @Override
public void onMapReady(GoogleMap googleMap) {
    Polyline polyline1 = googleMap.addPolyline(new PolylineOptions()
            .clickable(true)
            .add(
                    new LatLng(-35.016,143.321),new LatLng(-32.491,147.309)));
    googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(-23.684,133.903),4));

}

有关更多详细信息,请访问enter link description here

,

我认为您应该尝试使用我的代码


async reloadResources() {
  this.resourceName = this.$router.currentRoute.params.resourceName || this.$router.currentRoute.name;
  if (this.resourceName) {
    let filters_backup = _.cloneDeep(this.$store.getters[`${this.resourceName}/filters`]);
    let filters_to_change = _.cloneDeep(filters_backup);
    filters_to_change.push({});
    await this.$store.commit(`${this.resourceName}/storeFilters`,filters_to_change);
    await this.$store.commit(`${this.resourceName}/storeFilters`,filters_backup);
  }
},

DownloadTask是我的如下所示的AsycTask

@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;

// Add a marker in Sydney and move the camera
mMap.setMyLocationEnabled(true);

//Adding marker between two coordinates
mMap.addMarker(place1);
mMap.addMarker(place2);

String url = getDirectionsUrl();
new DownloadTask().execute(url);
}

private String getDirectionsUrl()
{
    String str_origin = "origin="+57.6800907+","+12.0031394;
    String str_dest = "destination="+57.9576648+","+12.1188331;
    String sensor = "sensor=false";
    String parameters = str_origin+"&"+str_dest+"&"+sensor;
    String output = "json";
    String url = "https://maps.googleapis.com/maps/api/directions/"+output+"?"+parameters;
    return url;
}

ParserTask是用于在Google地图上绘制路径的新异步任务

private class DownloadTask extends AsyncTask<String,Void,String> {
    ProgressDialog dialog;
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dialog = new ProgressDialog(MapDetailActivity.this);
        dialog.setMessage("Please wait...");
        dialog.setCancelable(false);
        dialog.show();
        ISPROGRESS = true;
    }
    @Override
    protected String doInBackground(String... url) {
        String data = "";
        try{
            data = downloadUrl(url[0]);
        }catch(Exception e){
            //Log.e("XXX","Exception while downloading "+e.toString());
        }
        return data;
    }
    @Override
    protected void onPostExecute(String result)  {
        super.onPostExecute(result);
        dialog.dismiss();
        new ParserTask().execute(result);

    }
}

private String downloadUrl(String strUrl) throws IOException {
    String data = "";
    InputStream iStream = null;
    HttpURLConnection urlConnection = null;
    try{
        URL url = new URL(strUrl);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.connect();
        iStream = urlConnection.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
        StringBuffer sb  = new StringBuffer();
        String line = "";
        while( ( line = br.readLine())  != null)
        {
            sb.append(line);
        }
        data = sb.toString();
        br.close();
    }catch(Exception e){
        //Log.e("Exception while downloading url",e.toString());
    }finally{
        iStream.close();
        urlConnection.disconnect();
    }
    return data;
}

lastone是DirectionJSONParser是readymate类

private class ParserTask extends AsyncTask<String,Integer,List<List<HashMap<String,String>>> >
{
    @Override
    protected List<List<HashMap<String,String>>> doInBackground(String... jsonData)
    {
        JSONObject jObject;
        List<List<HashMap<String,String>>> routes = null;
        try{
            jObject = new JSONObject(jsonData[0]);
            DirectionsJSONParser parser = new DirectionsJSONParser();
            routes = parser.parse(jObject);
        }catch(Exception e){
            e.printStackTrace();
        }
        return routes;
    }

    @Override
    protected void onPostExecute(List<List<HashMap<String,String>>> result) {
        ArrayList<LatLng> points = null;
        //PolylineOptions lineOptions = null;
        MarkerOptions markerOptions = new MarkerOptions();
        String distance = "";
        String duration = "";

        if(result.size()<1){
            Toast.makeText(getApplicationContext(),"No Points",Toast.LENGTH_SHORT).show();
            return;
        }
        for(int i=0;i<result.size();i++){
            points = new ArrayList<LatLng>();
            //lineOptions = new PolylineOptions();

            List<HashMap<String,String>> path = result.get(i);

            for(int j=0;j<path.size();j++)
            {
                HashMap<String,String> point = path.get(j);

                if(j==0){
                    distance = (String)point.get("distance");
                    continue;
                }else if(j==1){
                    duration = (String)point.get("duration");
                    continue;
                }
                double lat = Double.parseDouble(point.get("lat"));
                double lng = Double.parseDouble(point.get("lng"));
                LatLng position = new LatLng(lat,lng);
                points.add(position);
            }
            // Adding all the points in the route to LineOptions
            lineOptions.addAll(points);
            lineOptions.width(5);
            lineOptions.color(Color.RED);

        }
        //textView_distance.setText(distance); //if you want
        //textView_time.setText(duration); //if you want
        mMap.addPolyline(lineOptions);
        mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(Latitude,Longitude),15f));
        ISPROGRESS = false;
    }
}
,

在两个坐标之间绘制多段线需要几个步骤。

1-您需要点击此网址

strWord += whatever;

2-您需要解析响应并获取所有坐标列表,并将其输入到PolyLine。

我建议您使用自己的API KEY来看看此repo

本文链接:https://www.f2er.com/3138002.html

大家都在问