2013-03-22 45 views
1

我遵循了教程; http://www.androidhive.info/2012/08/android-working-with-google-places-and-maps-tutorial/Google Places +地圖代碼從v1更新爲v2

谷歌地方方面工作完美,但谷歌地圖代碼已過時。我不知道如何更新谷歌地圖代碼從v1到v2? 任何指針??

public class PlacesMapActivity extends MapActivity { 
    // Nearest places 
    PlacesList nearPlaces; 

    // Map view 
    MapView mapView; 

    // Map overlay items 
    List<Overlay> mapOverlays; 

    AddItemizedOverlay itemizedOverlay; 

    GeoPoint geoPoint; 
    // Map controllers 
    MapController mc; 

    double latitude; 
    double longitude; 
    OverlayItem overlayitem; 

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

     // Getting intent data 
     Intent i = getIntent(); 

     // Users current geo location 
     String user_latitude = i.getStringExtra("user_latitude"); 
     String user_longitude = i.getStringExtra("user_longitude"); 

     // Nearplaces list 
     nearPlaces = (PlacesList) i.getSerializableExtra("near_places"); 

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

     mapOverlays = mapView.getOverlays(); 

     // Geopoint to place on map 
     geoPoint = new GeoPoint((int) (Double.parseDouble(user_latitude) * 1E6), 
       (int) (Double.parseDouble(user_longitude) * 1E6)); 

     // Drawable marker icon 
     Drawable drawable_user = this.getResources() 
       .getDrawable(R.drawable.mark_red); 

     itemizedOverlay = new AddItemizedOverlay(drawable_user, this); 

     // Map overlay item 
     overlayitem = new OverlayItem(geoPoint, "Your Location", 
       "That is you!"); 

     itemizedOverlay.addOverlay(overlayitem); 

     mapOverlays.add(itemizedOverlay); 
     itemizedOverlay.populateNow(); 

     // Drawable marker icon 
     Drawable drawable = this.getResources() 
       .getDrawable(R.drawable.mark_blue); 

     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 
       geoPoint = new GeoPoint((int) (latitude * 1E6), 
         (int) (longitude * 1E6)); 

       // Map overlay item 
       overlayitem = new OverlayItem(geoPoint, place.name, 
         place.vicinity); 

       itemizedOverlay.addOverlay(overlayitem); 


       // calculating map boundary area 
       minLat = (int) Math.min(geoPoint.getLatitudeE6(), minLat); 
       minLong = (int) Math.min(geoPoint.getLongitudeE6(), minLong); 
       maxLat = (int) Math.max(geoPoint.getLatitudeE6(), maxLat); 
       maxLong = (int) Math.max(geoPoint.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)); 
     mapView.postInvalidate(); 

    } 

    @Override 
    protected boolean isRouteDisplayed() { 
     return false; 
    } 

} 

public class AddItemizedOverlay extends ItemizedOverlay<OverlayItem> { 

     private ArrayList<OverlayItem> mapOverlays = new ArrayList<OverlayItem>(); 

     private Context context; 

     public AddItemizedOverlay(Drawable defaultMarker) { 
      super(boundCenterBottom(defaultMarker)); 
     } 

     public AddItemizedOverlay(Drawable defaultMarker, Context context) { 
      this(defaultMarker); 
      this.context = context; 
     } 

     @Override 
     public boolean onTouchEvent(MotionEvent event, MapView mapView) 
     { 

      if (event.getAction() == 1) { 
       GeoPoint geopoint = mapView.getProjection().fromPixels(
        (int) event.getX(), 
        (int) event.getY()); 
       // latitude 
       double lat = geopoint.getLatitudeE6()/1E6; 
       // longitude 
       double lon = geopoint.getLongitudeE6()/1E6; 
       //Toast.makeText(context, "Lat: " + lat + ", Lon: "+lon, Toast.LENGTH_SHORT).show(); 
      } 
      return false; 
     } 

     @Override 
     protected OverlayItem createItem(int i) { 
      return mapOverlays.get(i); 
     } 

     @Override 
     public int size() { 
      return mapOverlays.size(); 
     } 

     @Override 
     protected boolean onTap(int index) { 
     OverlayItem item = mapOverlays.get(index); 
     AlertDialog.Builder dialog = new AlertDialog.Builder(this.context); 
     dialog.setTitle(item.getTitle()); 
     dialog.setMessage(item.getSnippet()); 
     dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, int which) { 
      } 
     }); 
     dialog.show(); 
     return true; 
     } 

     public void addOverlay(OverlayItem overlay) { 
      mapOverlays.add(overlay); 
     } 

     public void populateNow(){ 
      this.populate(); 
     } 
} 

public class NearbyActivity extends Activity{ 
    // flag for Internet connection status 
     Boolean isInternetPresent = false; 

     // Connection detector class 
     ConnectionDetector cd; 

     // Alert Dialog Manager 
     AlertDialogManager alert = new AlertDialogManager(); 

     // Google Places 
     GooglePlaces googlePlaces; 

     // Places List 
     PlacesList nearPlaces; 

     // GPS Location 
     GPSTracker gps; 

     // Button 
     Button btnShowOnMap; 

     // Progress dialog 
     ProgressDialog pDialog; 

     // Places Listview 
     ListView lv; 

     // ListItems data 
     ArrayList<HashMap<String, String>> placesListItems = new ArrayList<HashMap<String,String>>(); 


     // KEY Strings 
     public static String KEY_REFERENCE = "reference"; // id of the place 
     public static String KEY_NAME = "name"; // name of the place 
     public static String KEY_VICINITY = "vicinity"; // Place area name 




    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main3); 
     getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.window_title); 
     Button buttonNear = (Button) findViewById(R.id.buttonNearby);  
     buttonNear.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View arg0) { 
       //Starting a new Intent 
       Intent HomeScreen = new Intent(getApplicationContext(),HomeActivity.class); 
       startActivity(HomeScreen); 
      } 
      }); 




         cd = new ConnectionDetector(getApplicationContext()); 

         // Check if Internet present 
         isInternetPresent = cd.isConnectingToInternet(); 
         if (!isInternetPresent) { 
          // Internet Connection is not present 
          alert.showAlertDialog(NearbyActivity.this, "Internet Connection Error", 
            "Please connect to working Internet connection", false); 
          // stop executing code by return 
          return; 
         } 

         // creating GPS Class object 
         gps = new GPSTracker(this); 

         // check if GPS location can get 
         if (gps.canGetLocation()) { 
          Log.d("Your Location", "latitude:" + gps.getLatitude() + ", longitude: " + gps.getLongitude()); 
         } else { 
          // Can't get user's current location 
          alert.showAlertDialog(NearbyActivity.this, "GPS Status", 
            "Couldn't get location information. Please enable GPS", 
            false); 
          // stop executing code by return 
          return; 
         } 

         // Getting listview 
         lv = (ListView) findViewById(R.id.list); 

         // button show on map 
         btnShowOnMap = (Button) findViewById(R.id.btn_show_map); 

         // calling background Async task to load Google Places 
         // After getting places from Google all the data is shown in listview 
         new LoadPlaces().execute(); 

         /** Button click event for shown on map */ 
         btnShowOnMap.setOnClickListener(new View.OnClickListener() { 

          @Override 
          public void onClick(View arg0) { 
           Intent i = new Intent(getApplicationContext(), 
             PlacesMapActivity.class); 
           // Sending user current geo location 
           i.putExtra("user_latitude", Double.toString(gps.getLatitude())); 
           i.putExtra("user_longitude", Double.toString(gps.getLongitude())); 

           // passing near places to map activity 
           i.putExtra("near_places", nearPlaces); 
           // staring activity 
           startActivity(i); 
          } 
         }); 


         /** 
         * ListItem click event 
         * On selecting a listitem SinglePlaceActivity is launched 
         * */ 
         lv.setOnItemClickListener(new OnItemClickListener() { 

          @Override 
          public void onItemClick(AdapterView<?> parent, View view, 
            int position, long id) { 
           // getting values from selected ListItem 
           String reference = ((TextView) view.findViewById(R.id.reference)).getText().toString(); 

           // Starting new intent 
           Intent in = new Intent(getApplicationContext(), 
             SinglePlaceActivity.class); 

           // Sending place refrence id to single place activity 
           // place refrence id used to get "Place full details" 
           in.putExtra(KEY_REFERENCE, reference); 
           startActivity(in); 
          } 
         }); 
        } 

        /** 
        * Background Async Task to Load Google places 
        * */ 
        class LoadPlaces extends AsyncTask<String, String, String> { 

         /** 
         * Before starting background thread Show Progress Dialog 
         * */ 
         @Override 
         protected void onPreExecute() { 
          super.onPreExecute(); 
          pDialog = new ProgressDialog(NearbyActivity.this); 
          pDialog.setMessage(Html.fromHtml("<b>Search</b><br/>Loading Places...")); 
          pDialog.setIndeterminate(false); 
          pDialog.setCancelable(false); 
          pDialog.show(); 
         } 

         /** 
         * getting Places JSON 
         * */ 
         protected String doInBackground(String... args) { 
          // creating Places class object 
          googlePlaces = new GooglePlaces(); 

          try { 
           // Separeate your place types by PIPE symbol "|" 
           // If you want all types places make it as null 
           // Check list of types supported by google 
           // 
           String types = null; // Listing places only cafes, restaurants 

           // Radius in meters - increase this value if you don't find any places 
           double radius = 400; // 1000 meters 

           // get nearest places 
           nearPlaces = googlePlaces.search(gps.getLatitude(), 
             gps.getLongitude(), radius, types); 


          } catch (Exception e) { 
           e.printStackTrace(); 
          } 
          return null; 
         } 

         /** 
         * After completing background task Dismiss the progress dialog 
         * and show the data in UI 
         * Always use runOnUiThread(new Runnable()) to update UI from background 
         * thread, otherwise you will get error 
         * **/ 
         protected void onPostExecute(String file_url) { 
          // dismiss the dialog after getting all products 
          pDialog.dismiss(); 
          // updating UI from Background Thread 
          runOnUiThread(new Runnable() { 
           public void run() { 
            /** 
            * Updating parsed Places into LISTVIEW 
            * */ 
            // Get json response status 
            String status = nearPlaces.status; 

            // Check for all possible status 
            if(status.equals("OK")){ 
             // Successfully got places details 
             if (nearPlaces.results != null) { 
              // loop through each place 
              for (Place p : nearPlaces.results) { 
               HashMap<String, String> map = new HashMap<String, String>(); 

               // Place reference won't display in listview - it will be hidden 
               // Place reference is used to get "place full details" 
               map.put(KEY_REFERENCE, p.reference); 

               // Place name 
               map.put(KEY_NAME, p.name); 


               // adding HashMap to ArrayList 
               placesListItems.add(map); 
              } 
              // list adapter 
              ListAdapter adapter = new SimpleAdapter(NearbyActivity.this, placesListItems, 
                R.layout.list_item, 
                new String[] { KEY_REFERENCE, KEY_NAME}, new int[] { 
                  R.id.reference, R.id.name }); 

              // Adding data into listview 
              lv.setAdapter(adapter); 
             } 
            } 
            else if(status.equals("ZERO_RESULTS")){ 
             // Zero results found 
             alert.showAlertDialog(NearbyActivity.this, "Near Places", 
               "Sorry no places found. Try to change the types of places", 
               false); 
            } 
            else if(status.equals("UNKNOWN_ERROR")) 
            { 
             alert.showAlertDialog(NearbyActivity.this, "Places Error", 
               "Sorry unknown error occured.", 
               false); 
            } 
            else if(status.equals("OVER_QUERY_LIMIT")) 
            { 
             alert.showAlertDialog(NearbyActivity.this, "Places Error", 
               "Sorry query limit to google places is reached", 
               false); 
            } 
            else if(status.equals("REQUEST_DENIED")) 
            { 
             alert.showAlertDialog(NearbyActivity.this, "Places Error", 
               "Sorry error occured. Request is denied", 
               false); 
            } 
            else if(status.equals("INVALID_REQUEST")) 
            { 
             alert.showAlertDialog(NearbyActivity.this, "Places Error", 
               "Sorry error occured. Invalid Request", 
               false); 
            } 
            else 
            { 
             alert.showAlertDialog(NearbyActivity.this, "Places Error", 
               "Sorry error occured.", 
               false); 
            } 
           } 
          }); 

         } 

        } 
        @Override 
        public boolean onCreateOptionsMenu(Menu menu) { 
         getMenuInflater().inflate(R.menu.home, menu); 
         return true; 
        } 

} 
+0

您可以從開發者頁面讀取 - https://developers.google.com/maps/documentation/android/ – Anukool 2013-03-22 14:56:17

+0

只要按照V2的文檔。 V2比V1更容易實現。除去MapActivity,因爲你不再需要這些,現在一切都可以通過片段完成。 – Budius 2013-03-22 15:05:00

+0

v2被完全重寫。你應該一樣。就像Budius說的那樣,它比v1更容易。 – akaya 2013-03-22 15:53:27

回答

2

你可以通過這個博客文章中,我寫了一篇關於如何谷歌整合在您的應用中使用Map API v2:

Google Maps API V2

1

如果您還有任何疑問,請通過這篇文章:Google Map V2