简体   繁体   中英

how to call Android mapActivity OnTouchEvent and LocationManager/Geopoint

I'm a noob to android and i'm trying to develop a location based app. For some reason i can't get the LocationManager to establich my Geopoint to place a pin at my true location. i get an error stating that MapActivity couldn't get connection factory client. I followed this tutorial (http://thenewboston.org/watch.php?cat=6&number=144) verbatim so i don't understand why it is not working. Also if anyone could point me to any sample projects that implement google places api to find nearby establishments and and draw those location on mapview that would be greatly appreciated. Thanks in advance for any help!

Main 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 Layout

<?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>    

I followed this tutorial and it worked. I used part 1,2 and 5. Hope it helps!

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

in your CustomPinPoint.java just Override public boolean onTouchEvent(MotionEvent event, MapView mapView) method like this.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM