0

私はマップ アプリケーション [KML ファイルを読み込んで Google マップに表示する] を行っており、このサイトでここで説明されているクラスを使用していました。クラスを以下に示します。

私はいくつかの問題に 直面し

このリンクからこのクラスを取得しました kmlファイルを使用してマップにパスを描画する方法は?

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

参照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
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 に答える
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
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 に答える