Question

Hi I have been trying to get and pinpoint the location of the phone (user current location) however I have no luck. I hope somebody can help me with the code.

Just to add some more, I am receiving a "Couldn't get connection factory client" error. Does this have something to do with the ability to return the user location?

If it helps I have been following the tutorial by thenewboston.

Or does this have something to do with my API key? But I can receive the map properly, but cannot pinpoint the user's current location


The main code:

public class Map extends MapActivity implements LocationListener{

MapView map;
long start;
long stop;
MyLocationOverlay compass;
MapController controller;
int x,y;
GeoPoint touchedPoint;
Drawable d;
List<Overlay> overlayList;

LocationManager lm;
LocationListener ll;
String towers;
int lat = 0;
int longi = 0;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_map);
    map = (MapView)findViewById(R.id.mapview);
    map.setBuiltInZoomControls(true);

    touch t = new touch();
    overlayList = map.getOverlays();
    overlayList.add(t);
    compass = new MyLocationOverlay(Map.this, map);
    overlayList.add(compass);
    controller = map.getController();
    GeoPoint point = new GeoPoint(832332,4121093);
    controller.animateTo(point);
    controller.setZoom(8);


    d = getResources().getDrawable(R.drawable.pointer);

    //placing location
    lm =(LocationManager) getSystemService(Context.LOCATION_SERVICE);

    Criteria crit = new Criteria();
    towers = lm.getBestProvider(crit, false);
    Location loc = lm.getLastKnownLocation(towers);

    if(loc != null){
        lat = (int) (loc.getLatitude() *1E6);
        longi = (int)(loc.getLongitude()*1E6);
        GeoPoint location = new GeoPoint(lat, longi);
        OverlayItem overlayitem = new OverlayItem(location , "wassup", "2nd string");
        CustomPinPoint custom = new CustomPinPoint(d, Map.this);
        custom.insertPinPoint(overlayitem);
        overlayList.add(custom);

    }else{
        Toast.makeText(Map.this, "Location is null", Toast.LENGTH_LONG).show();
        lm.requestLocationUpdates(towers, 1500, 1, this);
    }


}


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

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

 }

I think you can ignore the alertdialog

public class touch extends Overlay {

    public boolean onTouchEvent(MotionEvent e, MapView m){
        if(e.getAction()== MotionEvent.ACTION_DOWN){
            start = e.getEventTime();
            x = (int) e.getX();
            y = (int) e.getY();
            touchedPoint = map.getProjection().fromPixels(x, y);

        }
        if(e.getAction()== MotionEvent.ACTION_UP){
            stop = e.getEventTime();
        }
        if(stop-start >1200){
            AlertDialog alert = new AlertDialog.Builder(Map.this).create();
            alert.setTitle("Option");
            alert.setMessage("Pick the option");
            alert.setCanceledOnTouchOutside(true);
            alert.setButton("Place pointer pinpoint", 
                    new DialogInterface.OnClickListener() {

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

                    OverlayItem overlayitem = new OverlayItem(touchedPoint , "wassup", "2nd string");
                    CustomPinPoint custom = new CustomPinPoint(d, Map.this);
                    custom.insertPinPoint(overlayitem);
                    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 t = Toast.makeText(getBaseContext(), display, Toast.LENGTH_LONG);
                                t.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(map.isSatellite()){
                        map.setSatellite(false);
                        map.setStreetView(true);
                    }else{
                        map.setStreetView(false);
                        map.setSatellite(true);
                    }

                }
            });

            alert.show();
            return true;


        }
        return false;

    }

}




@Override
protected boolean isRouteDisplayed() {
    // TODO Auto-generated method stub
    return false;
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_map, menu);
    return true;
}


@Override
public void onLocationChanged(Location l) {
    // TODO Auto-generated method stub
    lat = (int)(l.getLatitude()*1E6);
    longi = (int)(l.getLongitude()*1E6);
    GeoPoint location = new GeoPoint(lat, longi);
    OverlayItem overlayitem = new OverlayItem(location , "wassup", "2nd string");
    CustomPinPoint custom = new CustomPinPoint(d, Map.this);
    custom.insertPinPoint(overlayitem);
    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

}


 }

The CustomPinPoint code :

public class CustomPinPoint extends ItemizedOverlay<OverlayItem> {

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

//  tesst google code
public CustomPinPoint(Drawable defaultMarker) {
    super(boundCenterBottom(defaultMarker));
    // TODO Auto-generated constructor stub
}

public CustomPinPoint(Drawable defaultMarker, Context context) {
    // TODO Auto-generated constructor stub
    this(defaultMarker);  //original code


}

@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 item){
    pinpoints.add(item);
//  this.populate(); //  original code
//  test code
    populate();
}

@Override
protected boolean onTap(int index){
    OverlayItem item = pinpoints.get(index);
    AlertDialog.Builder dialog = new AlertDialog.Builder(c);
    dialog.setTitle(item.getTitle());
    dialog.setMessage(item.getSnippet());
    dialog.show();
    return true;

}

public void addOverlay(OverlayItem overlay) {
    // TODO Auto-generated method stub
    pinpoints.add(overlay);
    populate();
}



    }

XML code:

         <com.google.android.maps.MapView xmlns:android="http://schemas.android.com/apk/res/android"
             xmlns:tools="http://schemas.android.com/tools"
             android:id="@+id/mapview"
             android:enabled="true"
             android:clickable="true"
             android:layout_width="fill_parent"
             android:layout_height="fill_parent"
             android:apiKey="0t9rHfGlUPgisa8P9MRAsSxhRXTVCL0XJog7uiA"
             />
Was it helpful?

Solution 2

Well this is embarrassing, it turns out that my code is correct and the problem was that the device's GPS wasn't turned on. Well I hope my code can help anyone in need. Cheers!

OTHER TIPS

Here is the example how to do that easily, try to implement this logic into your project:

public class MyMapActivity extends MapActivity {
private MapView map;
private MapController controller;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.mymap);
    initMapView();
    initMyLocation();

            map.invalidate();
}

    private void initMapView() {
    map = (MapView) findViewById(R.id.map);
    controller = map.getController();
    map.setSatellite(true);
    map.setBuiltInZoomControls(true);
}
private void initMyLocation() {
    final MyLocationOverlay overlay = new MyLocationOverlay(this, map);
    overlay.enableMyLocation();
    //overlay.enableCompass(); // does not work in emulator
    overlay.runOnFirstFix(new Runnable() {
        public void run() {
            // Zoom in to current location
            controller.setZoom(15);
            controller.animateTo(overlay.getMyLocation());
    }});
}

}

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top