使用数组在地图上显示不同的点

时间:2012-10-29 14:02:58

标签: android

我正在创建一个应用程序,其中我有一个导航屏幕,用户可以在多个位置提供。 这些位置存储在数组字符串中。 我在地图类中使用该字符串,我想用标记显示地图上的位置。 仅显示存储在阵列中的最后一个位置。 请有人帮帮我。

我的导航课程

public class Navigatie extends Activity{

public static String plaats1;
public static String plaats2;
public GeoPoint p;
public static String[] plaats;
public int i = 0;
static final String[] COUNTRIES = new String[] 
         {
            "Antwerpen", "Aalst", "Aartselaar", "Brussel", "Charleroi","duinkerke", "Gent", "Hasselt", "Ieper", ""
         };

// Here we create the layout, everything that's needed on the form is loaded in here.
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.navigatie);

    // Create an instance of the AutoCompleteTextView which is created in the layout file
     AutoCompleteTextView textView=(AutoCompleteTextView)findViewById(R.id.autocomplete);
     // Create an ArrayAdapter which we are using to autocomplete the textview
     ArrayAdapter<String>adapter=new ArrayAdapter<String>(this,R.layout.item_list,COUNTRIES);
     // put the adapter created above in the AutoCompleteTextView
     textView.setAdapter(adapter);

    // We create a new ImageButton which links to the map.java class 
    ImageButton imageButton = (ImageButton) findViewById(R.id.imageButton1);
    // We give a onclicklistener method to the button imageButton
    imageButton.setOnClickListener(new OnClickListener() {

        // if the imageButton is clicked we start a new activity called "Map"
        public void onClick(View v) {
            /*
            for (int j = 0; j<plaats.length; j++)
            {
                Map.plaats[j] = plaats[j];
            }
            */
            startActivity(new Intent(Navigatie.this, Map.class));
        }
    });

    Button add = (Button)findViewById(R.id.toevoegen);

    add.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            EditText text1 = (EditText)findViewById(R.id.autocomplete);
            plaats1 = text1.getText().toString();

            if (plaats1 != "")
            {
            EditText text2 = (EditText)findViewById(R.id.editText1);

            text2.append(plaats1 + "\n");

            plaats = new String[20];
            plaats[i] = plaats1;
            Toast.makeText(Navigatie.this,  plaats[i], Toast.LENGTH_SHORT).show();
            i++;
            text1.setText("");
            }
        }
    });

    Button clear = (Button)findViewById(R.id.verwijderen);

    clear.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            EditText text2 = (EditText)findViewById(R.id.editText1);
            text2.setText("");
            Arrays.fill(plaats, null);
        }
    });
}

}

我的地图课程:

public class Map extends MapActivity {
private MapView mapView;
private MapController mc;
LocationManager locMgr;
MyLocationListener locLstnr;
private TextView tvlat;
private TextView tvlong;
public Navigatie nav;
public String locatie;
public int coordinates[] = new int[100];
public int counter = 0;
int gplat;
int gplon;
static final String[] COUNTRIES = new String[] 
     {
        "Antwerpen", "Aalst", "Aartselaar", "Brussel",    "Charleroi","duinkerke", "Gent", "Hasselt", "Ieper", ""
     };

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) 
{
 super.onCreate(savedInstanceState);
 // set the layout screen to map
 setContentView(R.layout.map);

 // Create an instance of the AutoCompleteTextView which is created in the layout file
 AutoCompleteTextView textView=(AutoCompleteTextView)findViewById(R.id.autocomplete_country);
 // Create an ArrayAdapter which we are using to autocomplete the textview
 ArrayAdapter<String>adapter=new ArrayAdapter<String>(this,R.layout.item_list,COUNTRIES);
 // put the adapter created above in the AutoCompleteTextView
 textView.setAdapter(adapter);

 // Setting the mapview1 to the instance of MapView
 mapView = (MapView) findViewById(R.id.mapview1);
 // giving a controller to mc
 mc = mapView.getController();

 // String location2 = Navigatie.getVariable();

 for (int i = 0; i<Navigatie.plaats.length; i++)
 {
     if(Navigatie.plaats[i]!=null && !Navigatie.plaats[i].equals(""))
     {
         FindLocation(Navigatie.plaats[i]); 
     }
     else
     {
         System.out.println("Locatie niet gevonden");
     }
 }

 // create an instance of the find button created in the layout file
 Button btn_find = (Button) findViewById(R.id.btn_find);

 // Defining button click event listener for the find button
 OnClickListener findClickListener = new OnClickListener() 
 {
     public void onClick(View v) 
     {
         // Getting reference to EditText to get the user input location
         EditText etLocation = (EditText) findViewById(R.id.autocomplete_country);

         // Getting user input location
         String location = etLocation.getText().toString();

         if(location!=null && !location.equals(""))
         {
             Toast.makeText(Map.this, "Inzoomend op " + location, Toast.LENGTH_SHORT).show();
            new GeocoderTask().execute(location);
         }
         else
         {
             Toast.makeText(Map.this, "Locatie niet gevonden", Toast.LENGTH_SHORT).show();
         }
     }
 };

 // Setting button click event listener for the find button
 btn_find.setOnClickListener(findClickListener);

 // redraws the map
 mapView.invalidate();

 // sets the built in zoomcontrols on the screen
 mapView.setBuiltInZoomControls(true);

 Drawable makerDefault = this.getResources().getDrawable(R.drawable.pushpin);
 MirItemizedOverlay itemizedOverlay = new MirItemizedOverlay(makerDefault);
 GeoPoint point = null;

 for (int i = 0; i<100; i++)
 {
     point = new GeoPoint(coordinates[i], coordinates[i+1]);
     OverlayItem overlayItem = new OverlayItem(point, "new place added", null);
     itemizedOverlay.addOverlayItem(overlayItem);
     i++;
 }
 mapView.getOverlays().add(itemizedOverlay);
 MapController mc = mapView.getController();
 mc.setCenter(point);

 /*
String provider = LocationManager.GPS_PROVIDER; 
locMgr = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locLstnr = new MyLocationListener();
locMgr.requestSingleUpdate(provider, null);
  */

 List<Overlay> mapOverlays = mapView.getOverlays();
 Projection projection = mapView.getProjection();

}

// when the form is created we put in the menu from the resources menu.
@Override
public boolean onCreateOptionsMenu(Menu menu) 
{
    // we get the menu called main from the resources menu
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

// we set the options for the menu parts
@Override
public boolean onOptionsItemSelected(MenuItem item) 
{
    switch (item.getItemId()) 
    {
    // if my location is touched, this code is executed
    case R.id.my_location:
         // creates a toast that displays "moving to current location"
         Toast.makeText(Map.this, "Moving To Current location", Toast.LENGTH_SHORT).show();
         String provider = LocationManager.GPS_PROVIDER; 
            locMgr = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
            locLstnr = new MyLocationListener();
            locMgr.requestSingleUpdate(provider, null);
         // locLstnr.gpsCurrentLocation();
         return true;
    // if normal view is touched, this code is executed
    case R.id.normalview:
         // creates a toast that displays "Map Normal Street View"
         Toast.makeText(Map.this, "Map Normal Street View", Toast.LENGTH_SHORT).show();
         // if the satellite view is enabled, we disable the satellite view so the normal view popups again
         if(mapView.isSatellite()==true){
         mapView.setSatellite(false);
         }
         return true;
    case R.id.satellite:
         // creates a toast that displays "Map Satellite view"
         Toast.makeText(Map.this, "Map Satellite View", Toast.LENGTH_SHORT).show();
         // if the satellite view is disabled we enable the satellite view
         if(mapView.isSatellite()==false){
         mapView.setSatellite(true);
    }

}
return true;

}

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


public class MyLocationListener implements LocationListener
{
    public void onLocationChanged(Location loc)
    {
        loc.getLatitude();
        loc.getLongitude();
        String Text = "My current location is: " +
                "Latitud = " + loc.getLatitude() +
                "Longitud = " + loc.getLongitude();
        Toast.makeText( getApplicationContext(), Text, Toast.LENGTH_SHORT).show();

        String coordinates[] = {""+loc.getLatitude(), ""+loc.getLongitude()};
        double lat = Double.parseDouble(coordinates[0]);
        double lng = Double.parseDouble(coordinates[1]);

        GeoPoint p = new GeoPoint(
                (int) (lat * 1E6),
                (int) (lng * 1E6));

        mc.animateTo(p);
        mc.setZoom(7);
        mapView.invalidate();


    }

    public void onProviderDisabled(String provider)
    {
        Toast.makeText( getApplicationContext(),
                "Gps Disabled",
                Toast.LENGTH_SHORT ).show();
    }

    public void onProviderEnabled(String provider)
    {
        Toast.makeText( getApplicationContext(),
                "Gps Enabled",
                Toast.LENGTH_SHORT).show();
    }

    public void onStatusChanged(String provider, int status, Bundle extras)
    {
    }
}


// My overlay Class starts
class MyMapOverlays extends com.google.android.maps.Overlay
{   
    GeoPoint location = null;

    public MyMapOverlays(GeoPoint location)
    {
        super();
        this.location = location;
    }

    @Override
    public void draw(Canvas canvas, MapView mapView, boolean shadow)
    {
        super.draw(canvas, mapView, shadow);
        // translate the screen pixels
        Point screenPoint = new Point();
        mapView.getProjection().toPixels(this.location, screenPoint);
        //add the image
        canvas.drawBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.pushpin),
                screenPoint.x, screenPoint.y , null); //Setting the image &nbsp;location on the screen (x,y).
    }
}
// My overlay Class ends

private class MirItemizedOverlay extends ItemizedOverlay 
{
    private List<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
    public MirItemizedOverlay(Drawable defaultMarker) 
    {
        super(boundCenterBottom(defaultMarker));
    }

    @Override
    protected OverlayItem createItem(int i) 
    {
        return mOverlays.get(i);
    }
    @Override
    public int size() 
    {
        return mOverlays.size();
    }
    public void addOverlayItem(OverlayItem overlayItem) 
    {
        mOverlays.add(overlayItem);
        populate();
    }
    public void addOverlayItem(int lat, int lon, String title) 
    {
        GeoPoint point = new GeoPoint(lat, lon);
        OverlayItem overlayItem = new OverlayItem(point, title, null);
        addOverlayItem(overlayItem);
    }

    /*
    @Override
    public boolean onTouchEvent(MotionEvent event, MapView mapView)
    {
        //---when user lifts his finger---
        if (event.getAction() == 1) 
        {
            GeoPoint p = mapView.getProjection().fromPixels(
            (int) event.getX(),
            (int) event.getY());

            Toast.makeText(getBaseContext(),
            p.getLatitudeE6() / 1E6 + "," +
                    p.getLongitudeE6() /1E6 ,
                    Toast.LENGTH_SHORT).show();

            Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
            try 
            {
                List<Address> addresses = geoCoder.getFromLocation(p.getLatitudeE6() / 1E6, p.getLongitudeE6() / 1E6, 1);

                String strCompleteAddress= "";
                if (addresses.size() > 0)
                {
                    for (int i=0; i<addresses.get(0).getMaxAddressLineIndex();i++)
                    strCompleteAddress+= addresses.get(0).getAddressLine(i) + "\n";
                }
                Log.i("MyLocTAG => ", strCompleteAddress);
                Toast.makeText(getBaseContext(), strCompleteAddress, Toast.LENGTH_LONG).show();
            }
            catch (IOException e) 
            {
                Log.i("MyLocTAG => ", "this is the exception part");
                e.printStackTrace();
            }
            return true;
        }
        else
        return false;
    }*/
}

//An AsyncTask class for accessing the GeoCoding Web Service
private class GeocoderTask extends AsyncTask<String, Void, List<Address>>
{
    protected List<Address> doInBackground(String... locationName) 
    {
        // Creating an instance of Geocoder class
        Geocoder geocoder = new Geocoder(getBaseContext());
        List<Address> addresses = null;

        try {
            //Getting a maximum of 3 Address that matches the input text
            addresses = geocoder.getFromLocationName(locationName[0], 3);
        } 
        catch (IOException e) {
        e.printStackTrace();
        }
        return addresses;
    }

    protected void onPostExecute(List<Address> addresses) 
    {
        //Getting Reference to MapView of the layout activity_main
        MapView mapView = (MapView) findViewById(R.id.mapview1);

        // Setting ZoomControls
        mapView.setBuiltInZoomControls(true);

        // Getting MapController for the MapView
        MapController mc = mapView.getController();

        // Getting Drawable object corresponding to a resource image
        Drawable drawable = getResources().getDrawable(R.drawable.pushpin);

        // Getting Overlays of the map
        List<Overlay> overlays = mapView.getOverlays();

        // Creating an ItemizedOverlay
        LocationOverlay locationOverlay = new LocationOverlay(drawable,getBaseContext());

        // Clearing the overlays
        overlays.clear();

        if(addresses==null || addresses.size()==0)
        {
            Toast.makeText(getBaseContext(), "No Location found", Toast.LENGTH_SHORT).show();

            // Redraws the map to clear the overlays
            mapView.invalidate();
        }

        // Adding Markers on Google Map for each matching address
        for(int i=0;i<addresses.size();i++)
        {
            Address address = (Address) addresses.get(i);

            // Creating an instance of GeoPoint, to display in Google Map
            GeoPoint p = new GeoPoint((int)(address.getLatitude()*1E6), (int)(address.getLongitude()*1E6));

            String addressText = String.format("%s, %s",
                address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
                address.getCountryName());

            // Creating an OverlayItem to mark the point
            OverlayItem overlayItem = new OverlayItem(p, "Location",addressText);

            // Adding the OverlayItem in the LocationOverlay
            locationOverlay.addOverlay(overlayItem);

            // Adding locationOverlay to the overlay
            overlays.add(locationOverlay);

            // Locate the first location
            if(i==0)
            mc.animateTo(p);
            mc.setZoom(15);
        }

        // Redraws the map
        mapView.invalidate();
    }
}

public void FindLocation(String plaats)
{

    Geocoder geoCoder = new Geocoder(this, Locale.getDefault());    
    try {
        List<Address> addresses = geoCoder.getFromLocationName(
            plaats, 5);
        //String add = "";
        if (addresses.size() > 0) {
            coordinates[counter] = (int) (addresses.get(0).getLatitude() * 1E6);
            counter++;
            coordinates[counter] = (int) (addresses.get(0).getLongitude() * 1E6);
            counter++;
        }    
    } catch (IOException e) {
        e.printStackTrace();
    }
}   

}

1 个答案:

答案 0 :(得分:0)

一些提示:

  • 在FindLocation上添加一个else以捕获未找到的位置:

    public void FindLocation(String plaats){

            Geocoder geoCoder = new Geocoder(this, Locale.getDefault());    
            try {
                List<Address> addresses = geoCoder.getFromLocationName(
                plaats, 5);
            //String add = "";
            if (addresses.size() > 0) {
                coordinates[counter] = (int) (addresses.get(0).getLatitude() * 1E6);
                counter++;
                coordinates[counter] = (int) (addresses.get(0).getLongitude() * 1E6);
                counter++;
            } else {
               Log.v(TAG, "Site " + plaats + " not found!");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }  
    

同样在onCreate()循环已定义的位置,而不是整个数组:

 for (int i = 0; i<count; i+=2)
 {
     point = new GeoPoint(coordinates[i], coordinates[i+1]);
     OverlayItem overlayItem = new OverlayItem(point, "new place added", null);
     itemizedOverlay.addOverlayItem(overlayItem);
 }