0

我是一个菜鸟,试图用谷歌地方开发一个基于位置的应用程序。我可以将我当前的位置添加到 ovelay 中,但我无法弄清楚我做错了什么,所以我可以将位置 api 结果添加到我的叠加层中。我的查询在我的网络浏览器中成功,但不是我的应用程序我得到 reQuest Deined 。如果有人可以提供帮助,将不胜感激。先感谢您!

主要活动:

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;
}
}

自定义PinPoint 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();
}

}
4

2 回答 2

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为了确保你调用 super 的 populate()。不知道它是否会有所不同。


编辑:好吧,在玩了你的代码之后,我发现了一些东西。首先,你的查询没有返回任何结果。当我keyword=gold从 URL 中删除时,它开始返回结果。

我对你的坐标、地理点到位置和其他东西有点困惑,第一个结果,使用你的代码被放置在非洲附近的海中。我想那不是你的商店所在的地方。但是,它的坐标是 81,74 或类似的东西。几乎没有一个精确的坐标。也许您应该尝试将它乘以 1E6,就像您在 for 循环之前所做的那样。

但是关于你原来的问题。在进行了我之前告诉你的更改后,它不起作用。但恢复到您的原始代码,它确实如此。问题是您根本没有使用原始 URL 获得任何结果。一旦我更改了 URL,它就会接收位置并绘制标记(尽管您需要稍微修改一下以正确显示它)

希望对你也有用

于 2012-08-03T07:53:06.523 回答
1

在彻底解决了您的问题之后,这是一个非常简单的错误:D

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

您只需将overlaylat0 乘以1E6,然后对overlaylng0 执行相同的操作。

于 2013-02-09T05:10:42.640 回答