2012-08-01 108 views
0

我是一個noob嘗試開發一個基於位置的應用程序與谷歌的地方。我可以添加我的當前位置ovelay,但我無法弄清楚我做錯了什麼,所以我可以將位置api結果添加到我的覆蓋圖中。我的查詢在我的瀏覽器中成功,但不是我的應用程序,我得到了reQuest Deined。如果有人可以幫助它,將不勝感激。先謝謝你!如何添加Google Places API結果以覆蓋地圖?

主要活動:

package com.example.fdu; 

public class FindDealer extends MapActivity implements LocationListener { 
MapView finddealer; 
long start; 
long stop; 
MyLocationOverlay compass; 
MapController controller; 
int x, y; 
GeoPoint touchedPoint; 
Drawable delta, zulu; 
List<Overlay> overlayList; 
LocationManager lm; 
String towers; 
int lat; 
int lon; 



@Override 
protected void onCreate(Bundle savedInstanceState) { 
    // TODO Auto-generated method stub 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.finddealer); 
    finddealer = (MapView) findViewById(R.id.mvFindDealer); 
    finddealer.setBuiltInZoomControls(true); 

    Touchy tango = new Touchy(); 
    overlayList = finddealer.getOverlays(); 
    overlayList.add(tango); 
    compass = new MyLocationOverlay(FindDealer.this, finddealer); 
    overlayList.add(compass); 
    controller = finddealer.getController(); 
    GeoPoint point = new GeoPoint(51643234, 7848593);//<--Germany 

    controller.setZoom(12); 
    finddealer.invalidate();//<--New 

    delta = getResources().getDrawable(R.drawable.map_pin_48); 
    zulu= getResources().getDrawable(R.drawable.ic_launcher); 

    //placing pinpoint at location 
    lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);  
    Criteria crit = new Criteria(); 
    towers = lm.getBestProvider(crit, false); 
    Location location = lm.getLastKnownLocation(towers); 
    if(location != null){ 
     lat = (int) (location.getLatitude()*1E6); 
     lon = (int) (location.getLongitude()*1E6);   
     GeoPoint ourLocation = new GeoPoint(lat, lon); 
     controller.animateTo(ourLocation); 
     OverlayItem oscar = new OverlayItem(ourLocation, "What's Up", "Homie"); 
     CustomPinPoint custom = new CustomPinPoint(delta, FindDealer.this); 
     custom.InsertPinpoint(oscar); 
     overlayList.add(custom);  

     String googlelat = String.valueOf((int) (location.getLatitude()*1E6)); 
     String googlelon = String.valueOf((int) (location.getLongitude()*1E6));  
     String googleplacesapi = "https://maps.googleapis.com/maps/api/place/search/json?location=" + googlelat + "," + googlelon + "&radius=50000&type=store&keyword=gold&sensor=false&key=My Key Redacted"; 

     try {   
      JSONObject googleObject = StoresNearMe.getJSONfromURL(googleplacesapi); 
      JSONArray parsedGoogle = googleObject.getJSONArray("results"); 
      if(parsedGoogle.equals(null)){ 
       Toast.makeText(FindDealer.this, "Unable to locate tower", Toast.LENGTH_SHORT).show(); 
      }else{ 
      for (int i = 0; i < parsedGoogle.length(); i++) { 
      JSONObject parsedlocales = parsedGoogle.getJSONObject(i); 
      if (i == 0){ 
       JSONObject geometrylocation = parsedlocales.getJSONObject("geometry").getJSONObject("location"); 
       String lat0 = geometrylocation.getString("lat"); 
       String lng0 = geometrylocation.getString("lng"); 
       double overlaylat0 = Double.parseDouble(lat0); 
       double overlaylng0 = Double.parseDouble(lng0); 
       GeoPoint resultLocation0 = new GeoPoint((int) (overlaylat0), (int) (overlaylng0));      
       OverlayItem whiskey = new OverlayItem(resultLocation0, "What's Up", "Homie"); 
       CustomPinPoint custom0 = new CustomPinPoint(zulu, FindDealer.this); 
       custom0.InsertPinpoint(whiskey); 
       overlayList.add(custom0); 
       break; 
      } 
      if (i == 1){ 
       JSONObject geometrylocation = parsedlocales.getJSONObject("geometry").getJSONObject("location"); 
       String lat1 = geometrylocation.getString("lat"); 
       String lng1 = geometrylocation.getString("lng"); 
       double overlaylat1 = Double.parseDouble(lat1); 
       double overlaylng1 = Double.parseDouble(lng1); 
       GeoPoint resultLocation1 = new GeoPoint((int) (overlaylat1),(int) (overlaylng1));      
       OverlayItem foxtrot = new OverlayItem(resultLocation1, "What's Up", "Homie"); 
       CustomPinPoint custom1 = new CustomPinPoint(zulu, FindDealer.this); 
       custom1.InsertPinpoint(foxtrot); 
       overlayList.add(custom1); 
       break; 
      } 
      if (i == 2){ 
       JSONObject geometrylocation = parsedlocales.getJSONObject("geometry").getJSONObject("location"); 
       String lat2 = geometrylocation.getString("lat"); 
       String lng2 = geometrylocation.getString("lng"); 
       double overlaylat2 = Double.parseDouble(lat2); 
       double overlaylng2 = Double.parseDouble(lng2); 
       GeoPoint resultLocation2 = new GeoPoint((int) (overlaylat2),(int) (overlaylng2));      
       OverlayItem hotel = new OverlayItem(resultLocation2, "What's Up", "Homie"); 
       CustomPinPoint custom2 = new CustomPinPoint(zulu, FindDealer.this); 
       custom2.InsertPinpoint(hotel); 
       overlayList.add(custom2); 
       break; 
      } 
      } 
      }    
     } catch (JSONException e) { 
     // Log.d("log_tag","JSON parsing error - Google Places Api:" + e.getMessage()); 
     }      

    }else{ 
     Toast.makeText(FindDealer.this, "Couldn't get provider", Toast.LENGTH_SHORT).show(); 
    } 

} 



@Override 
protected void onPause() { 
    // TODO Auto-generated method stub 
    compass.disableCompass(); 
    super.onPause(); 
    lm.removeUpdates(this); 
    finish(); 
} 

@Override 
protected void onResume() { 
    // TODO Auto-generated method stub 
    compass.disableCompass(); 
    super.onResume(); 
    lm.requestLocationUpdates(towers, 500, 1, this); 
} 

@Override 
protected boolean isRouteDisplayed() { 
    // TODO Auto-generated method stub 
    return false; 
} 
class Touchy extends Overlay{ 
    public boolean onTouchEvent(MotionEvent echo, MapView mike){ 
     if(echo.getAction()==MotionEvent.ACTION_DOWN){ 
      start=echo.getEventTime(); 
      x = (int) echo.getX(); 
      y = (int) echo.getY(); 
      touchedPoint = finddealer.getProjection().fromPixels(x, y); 
     } 
     if(echo.getAction()==MotionEvent.ACTION_UP){ 
      stop=echo.getEventTime(); 
     } 
     if (stop - start > 1500) { 
      AlertDialog alert = new AlertDialog.Builder(FindDealer.this).create(); 
      alert.setTitle("Pick an Option"); 
      alert.setMessage("Hag"); 
      alert.setButton("place a pinpoint", new DialogInterface.OnClickListener() { 


       @Override 
       public void onClick(DialogInterface dialog, int which) { 
        // TODO Auto-generated method stub 

        OverlayItem oscar = new OverlayItem(touchedPoint, "What's Up", "Homie"); 
        CustomPinPoint custom = new CustomPinPoint(zulu, FindDealer.this); 
        custom.InsertPinpoint(oscar); 
        overlayList.add(custom); 

       } 
      }); 
      alert.setButton2("Get Address", new DialogInterface.OnClickListener() { 

       @Override 
       public void onClick(DialogInterface dialog, int which) { 
        // TODO Auto-generated method stub 
        Geocoder geocoder = new Geocoder(getBaseContext(), Locale.getDefault()); 
        try{ 
         List<Address> address = geocoder.getFromLocation(touchedPoint.getLatitudeE6()/1E6 , touchedPoint.getLongitudeE6()/1E6, 1); 
         if (address.size() > 0){ 
          String display = ""; 
          for (int i = 0; i < address.get(0).getMaxAddressLineIndex(); i++){         
           display += address.get(0).getAddressLine(i) + "\n"; 
          } 
          Toast yankee = Toast.makeText(getBaseContext(), display, Toast.LENGTH_LONG); 
          yankee.show(); 
         } 
        } catch (IOException e) { 
         // TODO Auto-generated catch block 
         e.printStackTrace(); 
        }finally{ 

        } 
       } 
      }); 
      alert.setButton3("Toggle View", new DialogInterface.OnClickListener() { 

       @Override 
       public void onClick(DialogInterface dialog, int which) { 
        // TODO Auto-generated method stub 
        if (finddealer.isSatellite()){ 
         finddealer.setSatellite(false); 
         finddealer.setStreetView(true); 
        }else{ 
         finddealer.setSatellite(true); 
         finddealer.setStreetView(false); 
        } 
       } 
      }); 
      alert.show(); 
      return true; 
     } 
     return false; 

    } 
} 
@Override 
public void onLocationChanged(Location l) { 
    // TODO Auto-generated method stub 
    lat = (int) (l.getLatitude()* 1E6); 
    lon = (int) (l.getLongitude()* 1E6); 
    GeoPoint ourLocation = new GeoPoint(lat, lon); 
    OverlayItem oscar = new OverlayItem(ourLocation, "What's Up", "Homie"); 
    CustomPinPoint custom = new CustomPinPoint(delta, FindDealer.this); 
    custom.InsertPinpoint(oscar); 
    overlayList.add(custom); 
} 

@Override 
public void onProviderDisabled(String provider) { 
    // TODO Auto-generated method stub 
    Toast.makeText(getApplicationContext(),"Gps Disabled", Toast.LENGTH_SHORT).show();//<--New 

} 

@Override 
public void onProviderEnabled(String provider) { 
    // TODO Auto-generated method stub 
    Toast.makeText(getApplicationContext(),"Gps Enabled", Toast.LENGTH_SHORT).show();//<--New 
} 

@Override 
public void onStatusChanged(String provider, int status, Bundle extras) { 
    // TODO Auto-generated method stub 
    Toast.makeText(FindDealer.this, "StatusChanged" +provider, Toast.LENGTH_SHORT).show(); 
} 
} 

房屋靠近我

public class StoresNearMe { 

public static JSONObject getJSONfromURL(String url){ 
    InputStream is = null; 
    String result = ""; 
    JSONObject googleObject = null; 

    //http post 
    try{ 
      HttpClient httpclient = new DefaultHttpClient(); 
      HttpPost httppost = new HttpPost(url); 
      HttpResponse response = httpclient.execute(httppost); 
      HttpEntity entity = response.getEntity(); 
      is = entity.getContent(); 

    }catch(Exception e){ 
      Log.e("log_tag", "Error in http connection "+e.toString()); 
    } 

    //convert response to string 
    try{ 
      BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); 
      StringBuilder sb = new StringBuilder(); 
      String line = null; 
      while ((line = reader.readLine()) != null) { 
        sb.append(line + "\n"); 
      } 
      is.close(); 
      result=sb.toString(); 
    }catch(Exception e){ 
      Log.e("log_tag", "Error converting result "+e.toString()); 
    } 

    try{ 

     googleObject = new JSONObject(result);    
    }catch(JSONException e){ 
      Log.e("log_tag", "Error parsing data "+e.toString()); 
    } 

    return googleObject; 
} 
} 

CustomPinPoint的Java

public class CustomPinPoint extends ItemizedOverlay<OverlayItem> { 

private ArrayList<OverlayItem> pinpoints = new ArrayList<OverlayItem>(); 
private Context charlie; 

public CustomPinPoint(Drawable defaultMarker) { 
    super(boundCenter(defaultMarker)); 
    // TODO Auto-generated constructor stub 
} 

public CustomPinPoint(Drawable mike, Context context) {  
    // TODO Auto-generated constructor stub 
    this(mike); 
    charlie = context; 
} 

@Override 
protected OverlayItem createItem(int i) { 
    // TODO Auto-generated method stub 
    return pinpoints.get(i); 
} 

@Override 
public int size() { 
    // TODO Auto-generated method stub 
    return pinpoints.size(); 
} 

public void InsertPinpoint(OverlayItem india){ 
    pinpoints.add(india); 
    this.populate(); 
} 

} 
+0

您是否收到任何錯誤? JSON解析錯誤通常在logcat中以橙色顯示,並且不會導致您的應用粉碎,因此很容易錯過。 – 2012-08-03 01:59:38

+0

@Lablabla沒有錯誤,唯一的警告是關於CursorWrapper ...遊標沒有事先關閉而終結。我得到了我的查詢在應用程序中工作,但它不會添加到覆蓋。我很難過。 – 2012-08-03 07:43:38

回答

1

在你CustomPinPoint構造你寫

public CustomPinPoint(Drawable mike, Context context) {  
    // TODO Auto-generated constructor stub 
    this(mike); 
    charlie = context; 
} 

你打電話的this(mike)代替super(mike) 所以你基本上從未稱這不會造成ItemizedOverlay

另外,我不知道,如果它的事項超級構造,但本教程http://about-android.blogspot.co.il/2010/03/steps-to-place-marker-in-map-overlay.html比較你的代碼,

CustomPinPoint custom = new CustomPinPoint(delta, FindDealer.this); 

應該

CustomPinPoint custom = new CustomPinPoint(delta, this); 

最後一件事,你打電話this.populate()在你的public void InsertPinpoint(OverlayItem india){ 因爲你沒有覆蓋它,它應該只有populate,以確保你調用超級的填充()。不知道它是否會有所不同。


編輯: 嗯,有些與您的代碼打後,我發現了一些東西.. 首先,查詢到任何結果。當我從URL中刪除keyword=gold時,它開始返回結果。

我有點困惑與你的座標,以GeoPoint的位置之類的東西,第一個結果,用你的代碼放置在非洲附近海域。我認爲這不是你的商店的地方。然而,它的協調是81,74或類似的東西。幾乎沒有確切的座標。也許你應該像在for循環之前一樣,把它乘以1E6。

但是對於你原來的問題。 完成我之前告訴過你的更改後,它不起作用。但恢復到您的原始代碼,它的確如此。問題是,你根本沒有得到你的原始URL的任何結果。一旦我改變了URL,它接收到的地方,並繪製了標記(雖然你需要修補一點用正確顯示它)

。希望對你太

+0

感謝您的回覆。剛剛嘗試了你的建議。沒有運氣。奇怪的是,我的OverLay Item奧斯卡看起來很好,表明我的真實位置。它只是威士忌,狐步舞和酒店,正在固執,不會出現。 – 2012-08-03 08:03:21

+0

我編輯了我的答案。恢復到您的原始代碼並嘗試。它適用於我 – 2012-08-03 12:22:20

+0

太棒了!你能否粘貼我的「原始」代碼。幾天前我發現了非洲問題。我忘了讓亞特蘭大的緯度爲負。無論如何,我認爲你用我之前的一個編輯(我的最後編輯是在你的第一個評論之前)進行調整,並且一旦我知道哪一個我將與你在同一頁上。非常感謝! – 2012-08-03 14:16:32

1

致力於通過你的問題會相當徹底後,它的一個非常簡單的錯誤:d

double overlaylat0 = Double.parseDouble(lat0); 
double overlaylng0 = Double.parseDouble(lng0) 

您只需通過1E6乘overlaylat0,並做相同的overlaylng0。

相關問題