【问题标题】:how to call Android mapActivity OnTouchEvent and LocationManager/Geopoint如何调用Android mapActivity OnTouchEvent 和 LocationManager/Geopoint
【发布时间】:2012-07-18 20:46:38
【问题描述】:

我是 android 的菜鸟,我正在尝试开发一个基于位置的应用程序。出于某种原因,我无法让 LocationManager 建立我的 Geopoint 以在我的真实位置放置一个图钉。我收到一条错误消息,指出 MapActivity 无法获取连接工厂客户端。我逐字遵循本教程(http://thenewboston.org/watch.php?cat=6&number=144)所以我不明白为什么它不起作用。此外,如果有人能指出任何实施 google Places api 以查找附近机构并在 mapview 上绘制这些位置的示例项目,那将不胜感激。提前感谢您的帮助!

主Java

public class FindDealer extends MapActivity implements LocationListener {
MapView finddealer;
long start;
long stop;
MyLocationOverlay compass;
MapController controller;
int x, y;
GeoPoint touchedPoint;
Drawable delta;
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.animateTo(point);
    controller.setZoom(6);

    delta = 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);
        OverlayItem oscar = new OverlayItem(ourLocation, "What's Up",     "Homie");
        CustomPinPoint custom = new CustomPinPoint(delta, FindDealer.this);
        custom.InsertPinpoint(oscar);
        overlayList.add(custom);
    }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(start - start > 3000){
            AlertDialog alert = new          AlertDialog.Builder(FindDealer.this).create();
            alert.setTitle("Pick");
            alert.setMessage("pick again");
            alert.setButton("Place pin", 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(delta, 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 zulu = Toast.makeText(getBaseContext(), display, Toast.LENGTH_LONG);
                            zulu.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

}

@Override
public void onProviderEnabled(String provider) {
    // TODO Auto-generated method stub

}

@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();
}

//Google Places API
public class StoresNearMe {

    private String result = "";  
    private String googleAPIKey = "AIzaSyBXMthQXq878M8RFYvi2rCA8qQTBcFX1i4"; 
    private String searchRadius = "50";
    private Location myLocation;
    final String TAG = getClass().getSimpleName();  

    public StoresNearMe(Location location){
        myLocation = location;
    }//StoresNearMe

    public String getStoresNearMe(){
        String result = "Nothing";
        result = callGoogleWebService(buildURLForGooglePlaces(myLocation));
        convertJSONtoArray(result);
        return result;
    }//getStoresNearMe


    private String callGoogleWebService(String url){  
            HttpClient httpclient = new DefaultHttpClient();  
            HttpGet request = new HttpGet(url);  
            //request.addHeader("deviceId", deviceId);  
            ResponseHandler<String> handler = new BasicResponseHandler();  
            try {  
                result = httpclient.execute(request, handler);  
            } catch (ClientProtocolException e) {  
                e.printStackTrace();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
            httpclient.getConnectionManager().shutdown();  
            return result;
    }//callWebService

    private String buildURLForGooglePlaces(Location location){
        String baseUrl = "https://maps.googleapis.com/maps/api/place/search/json?";
        String lat = String.valueOf(location.getLatitude());
        String lon = String.valueOf(location.getLongitude());
        //String type= "establishment|jewelry_store|store";
        String keyword= "coin|numismatic|coins|numismatics";
        String url = baseUrl + "location=" + lat + "," + lon + "&" +
                     "radius=" + searchRadius + "keyword" + keyword + "sensor=false" +
                     "&" + "key=" + googleAPIKey;
        Log.d(TAG,url);
        return url;`enter code here`
    }//buildURLForGooglePlaces

    private void convertJSONtoArray(String rawJSON){
        try {
            JSONObject completeJSONObj = new JSONObject(rawJSON);
            String json = completeJSONObj.toString();
            Log.d(TAG,json);
            JSONArray results = completeJSONObj.getJSONArray("results");
        } catch (JSONException e) {
            Log.d(TAG,"JSON parsing error - fix it:" + e.getMessage());
        }
    }//convertJSONtoArray
}//StoresNearMe

}

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

}

XML 布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<com.google.android.maps.MapView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:apiKey="My key Redacted" 
    android:id="@+id/mvFindDealer"
    android:enabled="true" 
    android:clickable="true"
    />

</LinearLayout>    

【问题讨论】:

    标签: android google-maps android-mapview touch-event google-places-api


    【解决方案1】:

    我按照本教程进行操作,并且效果很好。我使用了第 1,2 和 5 部分。希望对您有所帮助!

    http://mirnauman.wordpress.com/2012/01/30/using-google-maps-in-android-development-tutorial-part-1/

    【讨论】:

      【解决方案2】:

      在您的 CustomPinPoint.java 中只是 Override public boolean onTouchEvent(MotionEvent event, MapView mapView)这样的方法。

      public boolean onTouchEvent(MotionEvent 事件, MapView mapView) {
      //---当用户抬起手指时--- 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(); }
      返回假; }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-18
        • 1970-01-01
        • 2015-10-13
        • 2013-04-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多