0

My application is supposed to have the user enter latitude and longitude values and a MapActivity opens centered around those coordinates with a circle drawn over the area. For some reason, no matter what coordinate pair is sent to the MapActivity, he map is always centered around a point in the middle of the ocean near Africa.

This function of the application used to work just fine until recently, but the other function of the app works just fine. The user can also select a location to center the map around, and the code is essentially the same, except the latitude and longitude values that are put into the bundle for the MapActivity are hardcoded instead of being entered by the user.

What's even more confusing is that the MapActivity receives the values that user enters just fine, but it just doesn't move to that location. I used logcat to make sure the MapActivity was getting the correct values.

I am currently using Android Studio version 1.2.1.1

Here is the Map Activity code (edited to contain all of the code)

private GoogleMap mMap; // Might be null if Google Play services APK is not available.
private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
private Location mCurrentLocation;
private double targetLat;
private double targetLon;
private double latRandom;
private double lonRandom;
private int radius;
private int circleState;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_map);
    Bundle b = getIntent().getExtras();
    targetLat = b.getDouble("lat");
    targetLon = b.getDouble("lon");
    Log.i("MapActivity","targetLat = "+targetLat);
    Log.i("MapActivity","targetLon = "+targetLon);
    radius = getIntent().getExtras().getInt("rad");
    setUpMapIfNeeded();

    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addApi(LocationServices.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();


}

@Override
protected void onResume() {
    super.onResume();
    setUpMapIfNeeded();
}

/**
 * Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
 * installed) and the map has not already been instantiated.. This will ensure that we only ever
 * call {@link #setUpMap()} once when {@link #mMap} is not null.
 * <p/>
 * If it isn't installed {@link SupportMapFragment} (and
 * {@link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
 * install/update the Google Play services APK on their device.
 * <p/>
 * A user can return to this FragmentActivity after following the prompt and correctly
 * installing/updating/enabling the Google Play services. Since the FragmentActivity may not
 * have been completely destroyed during this process (it is likely that it would only be
 * stopped or paused), {@link #onCreate(Bundle)} may not be called again so we should call this
 * method in {@link #onResume()} to guarantee that it will be called.
 */
private void setUpMapIfNeeded() {
    // Do a null check to confirm that we have not already instantiated the map.
    if (mMap == null) {
        // Try to obtain the map from the SupportMapFragment.
        mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                .getMap();
        // Check if we were successful in obtaining the map.
        if (mMap != null) {
            setUpMap();
        }
    }
}

/**
 * This is where we can add markers or lines, add listeners or move the camera. In this case, we
 * just add a marker near Africa.
 * <p/>
 * This should only be called once and when we are sure that {@link #mMap} is not null.
 */
private void setUpMap() {
    mMap.setMapType(MAP_TYPE_HYBRID); //set map type

    double shiftFactor = .0001;
    int color = getIntent().getExtras().getInt("color");

    while(findDistance(targetLat,targetLon,targetLat+shiftFactor,targetLon+shiftFactor)<radius){
        shiftFactor+=.0001;
    }


    latRandom = (Math.random()*shiftFactor);
    lonRandom = (Math.random()*shiftFactor);
    int rand2 = (int)(Math.random()*2)+1;
    if(rand2==1){
        latRandom = 0 - latRandom;
    }
    rand2 = (int)(Math.random()*2)+1;
    if(rand2==1){
        lonRandom = 0 - lonRandom;
    }


    LatLng loc = new LatLng(targetLat+latRandom,targetLon + lonRandom); //lat and long values for target(shift)
    CircleOptions circOpt = new CircleOptions(); //circle appearance
    circOpt.center(loc).radius(radius);
    circOpt.strokeWidth(0);
    circOpt.fillColor(color);
    mMap.addCircle(circOpt);
    mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 19)); //move screen to target(shift)
    mMap.setMyLocationEnabled(true);
    circleState=3;

}
@Override
protected void onStart(){
    super.onStart();
    mGoogleApiClient.connect();
}
@Override
protected void onStop(){
    super.onStart();
    mGoogleApiClient.disconnect();
}

@Override
public void onConnected(Bundle bundle) {
    mLocationRequest = LocationRequest.create();
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    mLocationRequest.setInterval(1000);
    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}

@Override
public void onConnectionSuspended(int i) {
    Toast.makeText(this,"Connection Suspended", Toast.LENGTH_SHORT).show();
}

@Override
public void onLocationChanged(Location location) {
    double lat = location.getLatitude();
    double lon = location.getLongitude();
    double difference = findDistance(lat,lon,targetLat,targetLon);
    if(difference<radius && difference > 4&& circleState==3){
        mMap.clear();
        LatLng loc = new LatLng(targetLat+latRandom,targetLon + lonRandom); //lat and long values for target(shift)
        CircleOptions circOpt = new CircleOptions(); //circle appearance
        circOpt.center(loc).radius(radius);
        circOpt.strokeWidth(0);
        circOpt.fillColor(Color.argb(120, 0, 0, 255));
        mMap.addCircle(circOpt);
        circleState = 2;
    }
    else if(difference<4&&difference > 2 && circleState==2){
        mMap.clear();
        LatLng loc = new LatLng(targetLat,targetLon); //lat and long values for target(not shifted)
        CircleOptions circOpt = new CircleOptions(); //circle appearance
        circOpt.center(loc).radius(4); //Make smaller search circle
        circOpt.strokeWidth(0);
        circOpt.fillColor(Color.argb(120, 0, 255, 0));
        mMap.addCircle(circOpt);
        circleState = 1;
    }
    else if(difference<3&&circleState==1){
        mMap.addCircle(new CircleOptions().center(new LatLng(targetLat,targetLon)).radius(1).strokeWidth(0).fillColor(Color.RED));
        circleState=0;
    }

}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    Toast.makeText(this,"Connection Failed",Toast.LENGTH_SHORT).show();
}

//Precondition: two pairs of real coordinates
public double findDistance(double lat1,double lon1, double lat2, double lon2){
    final int EARTH_RADIUS = 6371000;
    double a = Math.sin(Math.toRadians(lat2 - lat1)/2)*Math.sin(Math.toRadians(lat2 - lat1)/2)+
            Math.cos(Math.toRadians(lat1))*Math.cos(Math.toRadians(lat2))*
                    Math.sin(Math.toRadians(lon2 - lon1)/2)*Math.sin(Math.toRadians(lon2 - lon1)/2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    return EARTH_RADIUS * c ; //Return the distance
}

}

Here is the code for the activity with the list of location to choose from with hardcoded values. There is only one location as of now

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_quest_select);
    listView = (ListView)findViewById(R.id.list);
    String [] places = new String[] {"Light"}; //add more presets here, add coordinates to switch statement
    ArrayAdapter<String>adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,android.R.id.text1,places);
    listView.setAdapter(adapter);
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            switch(position){
                case 0:
                    startMap(view,43.005993,-75.984314);
                    break;

                default:
                    Toast.makeText(getApplicationContext(), "Not a valid selection",Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    });
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_quest_select, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
public void startMap(View view,double latVal,double lonVal){
    Intent intent = new Intent(this, MapActivity.class);
    Bundle b = new Bundle();
    b.putDouble("lat",latVal);
    b.putDouble("lon", lonVal);
    b.putInt("rad", 50);
    b.putInt("color", Color.argb(120,0,255,0));
    intent.putExtras(b);
    startActivity(intent);
}

And finally here is the code in the activity in which the user enters the latitude and longitude values. (edited to contain entire code)

public class CustomOptions extends ActionBarActivity {
private Spinner colorSelect;
private EditText latSet;
private EditText lonSet;
private double lat, lon;
private SeekBar radSet;
private TextView currentRadius;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_custom_options);
    colorSelect = (Spinner) findViewById(R.id.spinner1);
    String [] colors = new String[]{"Red","Blue","Green","Orange"};
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,colors);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    colorSelect.setAdapter(adapter);
    latSet = (EditText)findViewById(R.id.editText);
    lonSet = (EditText)findViewById(R.id.editText2);
    radSet = (SeekBar)findViewById(R.id.seekBar);
    radSet.setProgress(50);
    radSet.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            currentRadius.setText(String.valueOf(radSet.getProgress())+"m");
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    });
    currentRadius = (TextView)findViewById(R.id.currentRadius);
    currentRadius.setText(radSet.getProgress() + "m");

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_custom_options, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
public void startMap(View view){

    if(checkValidity()&&Math.abs(lat)<=90&&Math.abs(lon)<=180) {
        Intent intent = new Intent(this, MapActivity.class);
        Bundle b = new Bundle();
        b.putDouble("lat",lat);
        b.putDouble("lon", lon);
        b.putInt("rad", radSet.getProgress());
        switch(colorSelect.getSelectedItemPosition()){
            case 0:
                b.putInt("color", Color.argb(120, 255, 0, 0));
                break;
            case 1:
                b.putInt("color", Color.argb(120, 0, 255, 0));
                break;
            case 2:
                b.putInt("color", Color.argb(120, 0, 0, 255));
                break;
            case 3:
                b.putInt("color",Color.argb(120,255,140,0));
                break;
            default:
                Toast.makeText(this,"Abort Captain!",Toast.LENGTH_SHORT).show();
                break;
        }
        intent.putExtras(b);
        Toast.makeText(this,"starting activity",Toast.LENGTH_SHORT).show();
        startActivity(intent);
    }
    else{

        if(Math.abs(lat)>90) Toast.makeText(this, "Invalid Latitude Value",Toast.LENGTH_SHORT).show();
        if(Math.abs(lat)>90) Toast.makeText(this, "Invalid Longitude Value",Toast.LENGTH_SHORT).show();

    }
}
public boolean checkValidity() {
    if(TextUtils.isEmpty(latSet.getText().toString())){
        Toast.makeText(this, "Set a latitude value",Toast.LENGTH_SHORT).show();
        return false;
    }
    if(TextUtils.isEmpty(lonSet.getText().toString())){
        Toast.makeText(this, "Set a longitude value",Toast.LENGTH_SHORT).show();
        return false;
    }
    return true;
}

}

Please let me know if there is anymore info I should provide.

Ben
  • 1
  • 2
  • It sounds like your values are (0, 0) at the time that you center the map and add the circle. Add logging for the values at the time that you perform this action. Also, add that code section to your question. – Daniel Nugent Jul 12 '15 at 19:15
  • I used logging to see how te lat and lon values were after the Map Activity is opened and the log shows that it receives the values correctly. I wouldn't think that centering the map is the problem because the activity with the list bundles lat and lon values in he same way as the custom activity, and that activity works perfectly fine. I want to edit my post to add more of my code to show exactly what I'm doing but I can't find how to edit the post for the life of me. – Ben Jul 15 '15 at 03:18
  • small edit link, lower left of your question. – Daniel Nugent Jul 15 '15 at 03:21
  • Thank you, I edited my question to contain all of the code for the Map Activity and the Custom Location activity – Ben Jul 15 '15 at 16:38
  • I ran your code, and it's working fine for me. I sent data through the Intent Extras to the MapActivity, and it placed a green circle on the map at that exact location, and was centered directly over the circle. – Daniel Nugent Jul 15 '15 at 18:45
  • Thank you!! I was going crazy wondering where I messed up, but it must be some strange problem with my device. – Ben Jul 16 '15 at 03:32
  • Sure, no problem! Try uninstalling the app and then run it, see if that makes it work! – Daniel Nugent Jul 16 '15 at 03:39
  • I tried reinstalling the app and it still didn't work on my old Samsung Galaxy S3 running 4.3. I then tried exporting the apk file, signed for debug, emailed it to myself and installed it, but the Map Activity then shows up completely grey! I tried the same thing with my new device (Asus zenfone 2 running the latest version of lolipop) and the same grey map came up. I'm really confused now, since I'm new to app development but I'd feel bad asking about all of these problems. – Ben Jul 16 '15 at 22:06
  • A grey map is almost always just a problem with using the API key. When you run from Android Studio it uses the default Android dev debug keystore. When you generate an apk, you probably created a new keystore, you need to get the SHA1 fingerprint for that keystore and add it to the API Key in the Developer Console. – Daniel Nugent Jul 16 '15 at 23:17
  • That's exactly what I did actually, I'll try to find the SHA1 fingerprint and hopefully the map will display the correct location on my new phone – Ben Jul 18 '15 at 03:05
  • take a look at this answer, it might help: http://stackoverflow.com/questions/30462081/android-google-maps-only-a-grey-background-as-apk/30462918#30462918 – Daniel Nugent Jul 18 '15 at 03:11

1 Answers1

0

So far your code looks fine. I guess you forget to move the map camera into the co-ordinates specified. Just try this,

LatLng my_latlng= new LatLng(-33.867, 151.206);
map.setMyLocationEnabled(true);
map.moveCamera(CameraUpdateFactory.newLatLngZoom(my_latlng, 13));

This will move the map camera view to the specific LatLng.

Prokash Sarkar
  • 11,723
  • 1
  • 37
  • 50