[英]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. 我是android的菜鸟,我正在尝试开发基于位置的应用。 For some reason i can't get the LocationManager to establich my Geopoint to place a pin at my true location.
由于某些原因,我无法让LocationManager建立我的Geopoint以便将图钉放置在我的真实位置。 i get an error stating that MapActivity couldn't get connection factory client.
我收到一条错误消息,指出MapActivity无法获得连接工厂客户端。 I followed this tutorial (http://thenewboston.org/watch.php?cat=6&number=144) verbatim so i don't understand why it is not working.
我逐字阅读了本教程(http://thenewboston.org/watch.php?cat=6&number=144),所以我不明白为什么它不起作用。 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.
另外,如果有人可以指出我任何实现google place api的示例项目,以查找附近的场所并在mapview上绘制这些位置,将不胜感激。 Thanks in advance for any help!
在此先感谢您的帮助!
Main Java 主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 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布局
<?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!
我使用了第1,2和5部分。希望对您有所帮助!
http://mirnauman.wordpress.com/2012/01/30/using-google-maps-in-android-development-tutorial-part-1/ 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. 在您的CustomPinPoint.java中,只需重写此类的公共布尔onTouchEvent(MotionEvent事件,MapView mapView)方法即可。
public boolean onTouchEvent(MotionEvent event, MapView mapView) {
public boolean onTouchEvent(MotionEvent event,MapView mapView){
//---when user lifts his finger--- if (event.getAction() == 1) {// ----当用户松开手指时---- if(event.getAction()== 1){
GeoPoint p = mapView.getProjection().fromPixels( (int) event.getX(), (int) event.getY());GeoPoint p = mapView.getProjection()。fromPixels((int)event.getX(),(int)event.getY()); Toast.makeText(getBaseContext(), p.getLatitudeE6() / 1E6 + "," + p.getLongitudeE6() /1E6 , Toast.LENGTH_SHORT).show();
Toast.makeText(getBaseContext(),p.getLatitudeE6()/ 1E6 +“,” + p.getLongitudeE6()/ 1E6,Toast.LENGTH_SHORT).show(); }
}
return false;返回false; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.