0

我正在做一个地图应用程序 [读取 KML 文件并将其显示到谷歌地图中],并且我正在使用本网站中已经讨论过的一个类。类如下所示。

我遇到了一些问题 1- R.layout.main >> 主中有错误
2- 也没有识别 dest[1] 和 dest[0]
3- 也没有识别出 drowpath 函数

我从这个链接获得了这个类How to draw a path on a map using kml file?

package com.test.map;

import com.test.map.R ; 
import java.net.URL;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.R;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;


import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.OverlayItem;

 public class DirectionMapActivity extends MapActivity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    MapView mapView = (MapView) findViewById(R.id.mapview);
    mapView.setBuiltInZoomControls(true);

    // Acquire a reference to the system Location Manager
    LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

    String locationProvider = LocationManager.NETWORK_PROVIDER;
    Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);

    StringBuilder urlString = new StringBuilder();
    urlString.append("http://maps.google.com/maps?f=d&hl=en");
    urlString.append("&saddr=");//from
    urlString.append( Double.toString(lastKnownLocation.getLatitude() ));
    urlString.append(",");
    urlString.append( Double.toString(lastKnownLocation.getLongitude() ));
    urlString.append("&daddr=");//to
    urlString.append( Double.toString((double)dest[0]/1.0E6 ));
    urlString.append(",");
    urlString.append( Double.toString((double)dest[1]/1.0E6 ));
    urlString.append("&ie=UTF8&0&om=0&output=kml");

    try{
        // setup the url
        URL url = new URL(urlString.toString());
        // create the factory
        SAXParserFactory factory = SAXParserFactory.newInstance();
        // create a parser
        SAXParser parser = factory.newSAXParser();
        // create the reader (scanner)
        XMLReader xmlreader = parser.getXMLReader();
        // instantiate our handler
        NavigationSaxHandler navSaxHandler = new NavigationSaxHandler();
        // assign our handler
        xmlreader.setContentHandler(navSaxHandler);
        // get our data via the url class
        InputSource is = new InputSource(url.openStream());
        // perform the synchronous parse           
        xmlreader.parse(is);
        // get the results - should be a fully populated RSSFeed instance, or null on error
        NavigationDataSet ds = navSaxHandler.getParsedData();

        // draw path
        drawPath(ds, Color.parseColor("#add331"), mapView );

        // find boundary by using itemized overlay
        GeoPoint destPoint = new GeoPoint(dest[0],dest[1]);
        GeoPoint currentPoint = new GeoPoint( new Double(lastKnownLocation.getLatitude()*1E6).intValue()
                                            ,new Double(lastKnownLocation.getLongitude()*1E6).intValue() );

        Drawable dot = this.getResources().getDrawable(R.drawable.pixel);
        MapItemizedOverlay bgItemizedOverlay = new MapItemizedOverlay(dot,this);
        OverlayItem currentPixel = new OverlayItem(destPoint, null, null );
        OverlayItem destPixel = new OverlayItem(currentPoint, null, null );
        bgItemizedOverlay.addOverlay(currentPixel);
        bgItemizedOverlay.addOverlay(destPixel);

        // center and zoom in the map
        MapController mc = mapView.getController();
        mc.zoomToSpan(bgItemizedOverlay.getLatSpanE6()*2,bgItemizedOverlay.getLonSpanE6()*2);
        mc.animateTo(new GeoPoint(
                (currentPoint.getLatitudeE6() + destPoint.getLatitudeE6()) / 2
                , (currentPoint.getLongitudeE6() + destPoint.getLongitudeE6()) / 2));

    } catch(Exception e) {
        Log.d("DirectionMap","Exception parsing kml.");
    }

}

@Override
protected boolean isRouteDisplayed() {
    // TODO Auto-generated method stub
    return false;

}
}
// and the rest of the methods in activity, e.g. drawPath() etc...
4

4 回答 4

0

以下是您的问题的一些答案:

1 . 您可以将新的布局文件调整为您自己的。非常像这样的东西

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout_fragement_mapview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/royal_blue"
    android:orientation="vertical" >

    <com.google.android.maps.MapView
        android:id="@+id/mapview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:apiKey="@string/maps_api_key"
        android:clickable="true"
        android:enabled="true" />

</RelativeLayout>

2 . 在dest[]中,有 2 个常数,例如

int[] dest = new int[] { 42500000, 1950000 };

只需将其作为类变量复制并粘贴到您的DirectionMapActivty

3 . 这里是drawPath(). 您可以将其用作您的方法DirectionMapActivity或另一个类中的静态方法

public abstract class Drawing {

   private static final String TAG = "Drawing";

   public static void drawPath(NavigationDataSet navSet, int color, MapView mMapView01) {

      Log.d(TAG, "map color before: " + color);

      // color correction for dining, make it darker
      if (color == Color.parseColor("#add331"))
         color = Color.parseColor("#6C8715");
      Log.d(TAG, "map color after: " + color);

      Collection overlaysToAddAgain = new ArrayList<Object>();
      for (Iterator<Overlay> iter = mMapView01.getOverlays().iterator(); iter.hasNext();) {
         Object o = iter.next();
         Log.d(TAG, "overlay type: " + o.getClass().getName());
         if (!RouteOverlay.class.getName().equals(o.getClass().getName())) {
            // mMapView01.getOverlays().remove(o);
            overlaysToAddAgain.add(o);
         }
      }
      mMapView01.getOverlays().clear();
      mMapView01.getOverlays().addAll(overlaysToAddAgain);

      String path = navSet.getRoutePlacemark().getCoordinates();
      Log.d(TAG, "path=" + path);
      if (path != null && path.trim().length() > 0) {
         String[] pairs = path.trim().split(" ");

         Log.d(TAG, "pairs.length=" + pairs.length);

         String[] lngLat = pairs[0].split(","); // lngLat[0]=longitude lngLat[1]=latitude
                                                // lngLat[2]=height

         Log.d(TAG, "lnglat =" + lngLat + ", length: " + lngLat.length);

         if (lngLat.length < 3)
            lngLat = pairs[1].split(","); // if first pair is not transferred completely, take
                                          // seconds pair //TODO

         try {
            GeoPoint startGP = new GeoPoint((int) (Double.parseDouble(lngLat[1]) * 1E6),
                  (int) (Double.parseDouble(lngLat[0]) * 1E6));
            mMapView01.getOverlays().add(new RouteOverlay(startGP, startGP, 1));
            GeoPoint gp1;
            GeoPoint gp2 = startGP;

            for (int i = 1; i < pairs.length; i++) // the last one would be crash
            {
               lngLat = pairs[i].split(",");

               gp1 = gp2;

               if (lngLat.length >= 2 && gp1.getLatitudeE6() > 0 && gp1.getLongitudeE6() > 0
                     && gp2.getLatitudeE6() > 0 && gp2.getLongitudeE6() > 0) {

                  // for GeoPoint, first:latitude, second:longitude
                  gp2 = new GeoPoint((int) (Double.parseDouble(lngLat[1]) * 1E6),
                        (int) (Double.parseDouble(lngLat[0]) * 1E6));

                  if (gp2.getLatitudeE6() != 22200000) {
                     mMapView01.getOverlays().add(new RouteOverlay(gp1, gp2, 2, color));
                     Log.d(TAG, "draw:" + gp1.getLatitudeE6() + "/" + gp1.getLongitudeE6() + " TO "
                           + gp2.getLatitudeE6() + "/" + gp2.getLongitudeE6());
                  }
               }
               // Log.d(myapp.APP,"pair:" + pairs[i]);
            }
            // routeOverlays.add(new RouteOverlay(gp2,gp2, 3));
            mMapView01.getOverlays().add(new RouteOverlay(gp2, gp2, 3));
         } catch (NumberFormatException e) {
            Log.e(TAG, "Cannot draw route.", e);
         }
      }
      // mMapView01.getOverlays().addAll(routeOverlays); // use the default color
      mMapView01.setEnabled(true);
   }

我希望这会有所帮助。玩得开心。

于 2012-09-30T04:46:24.717 回答
0

带有参考UseFull 链接

尝试这个

Intent mapIntent = new Intent(Intent.ACTION_VIEW, uri);
Uri uri1 = Uri.parse("geo:0,0?q=http://code.google.com/apis/kml/
documentation/KML_Samples.kml");
mapIntent.setData(uri1);
startActivity(Intent.createChooser(mapIntent, "Sample Map ")); 
于 2012-09-30T05:30:22.710 回答
0
try {
        String file = Environment.getExternalStorageDirectory().getPath() + "/campus.kml";
        String[] kmlfile = file.split("/");
        String kml=kmlfile[4];

            File myFile = new File(Environment.getExternalStorageDirectory().toString() + "/DCIM/Camera/campus");

           FileInputStream fIn = new FileInputStream(myFile);

         KmlLayer kmlLayer = new KmlLayer(mMap, fIn, getApplicationContext());

        KmlLayer kmlLayer = new KmlLayer(mMap, R.raw.campus, getApplicationContext());

        kmlLayer.addLayerToMap();
        moveCameraToKml(kmlLayer);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (XmlPullParserException e) {
        e.printStackTrace();
    }



}
于 2016-06-04T06:39:25.993 回答
0
public class KmlDemoActivity extends FragmentActivity {

    private GoogleMap mMap;
    private KmlLayer kmlLayer;
    private MarkerOptions markerOptions;
    private ArrayList<LatLng> arrayPoints = null;
    private int flag = 0;//which you draw Line=2 or Polygone=1

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_draw_route);

        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());

        if (status != ConnectionResult.SUCCESS) {
            int requestCode = 10;
            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
            dialog.show();
        } else {
            SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.map);
            mMap = fm.getMap();

            if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

                return;
            }
            mMap.setMyLocationEnabled(true);


            // Getting LocationManager object from System Service LOCATION_SERVICE
            LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

            // Creating a criteria object to retrieve provider
            Criteria criteria = new Criteria();

            // Getting the name of the best provider
            String provider = locationManager.getBestProvider(criteria, true);

            // Getting Current Location
            Location location = locationManager.getLastKnownLocation(provider);

            if (location != null) {
                onLocationChanged(location);
            }
            retrieveFileFromResourceArea();


        }
    }

    private void retrieveFileFromResourceArea() {
        flag = 1;
        try {
            KmlLayer kmlLayer = new KmlLayer(mMap, R.raw.campus, getApplicationContext());

            kmlLayer.addLayerToMap();
            moveCameraToKml(kmlLayer);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        }


        retrieveFileFromResourceLine();
    }

    private void retrieveFileFromResourceLine() {
        flag = 2;
        try {

            KmlLayer kmlLayer = new KmlLayer(mMap, R.raw.data, getApplicationContext());
            kmlLayer.addLayerToMap();
            moveCameraToKml(kmlLayer);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        }

    }


    public void onLocationChanged(Location location) {

        // Getting latitude of the current location
        double latitude = location.getLatitude();

        // Getting longitude of the current location
        double longitude = location.getLongitude();

        // Creating a LatLng object for the current location
        LatLng latLng = new LatLng(latitude, longitude);


    }


    private void moveCameraToKml(KmlLayer kmlLayer) {

        KmlContainer container = kmlLayer.getContainers().iterator().next();

        container = container.getContainers().iterator().next();

        KmlPlacemark placemark = container.getPlacemarks().iterator().next();
        final LatLngBounds.Builder builder = new LatLngBounds.Builder();
        if (flag == 1) {
            KmlPolygon polygon = (KmlPolygon) placemark.getGeometry();

            for (LatLng latLng : polygon.getOuterBoundaryCoordinates()) {
                builder.include(latLng);
            }

        }
        if (flag == 2) {
            KmlLineString lineString = (KmlLineString) placemark.getGeometry();

            for (LatLng latLng : lineString.getGeometryObject()) {
                builder.include(latLng);
            }
        }


        mMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
            @Override
            public void onMapLoaded() {
                mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 1));

            }
        });
    }
}
于 2016-06-04T06:34:27.963 回答