1

I am new to Android Google maps. I have written some code on maps following some tutorials but, i couldn't see the output. I generated and used map-key APIv2. please help me with the code.

Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.examp.nowmap"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="18" />

<permission
    android:name="com.examp.nowmap.permission.MAPS_RECEIVE"
    android:protectionLevel="signature" />

<uses-feature
    android:glEsVersion="0x00020000"
    android:required="true" />

<uses-permission android:name="com.examp.nowmap.package.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission   android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.examp.nowmap.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <meta-data
        android:name="com.google.android.maps.v2.API_KEY"
        android:value="AIzaSyBbMfnc3rVf89ie564M8VgKZpfpbLHKyKo" />
     </application>

</manifest>

MainActivity.java

package com.examp.nowmap;

@SuppressLint("NewApi")
public class MainActivity extends Fragment {

private Location currentLocation = null;
private LocationManager locationManager;
private GeoPoint currentPoint;

TextView location1;

ArrayList<LatLng> markerPoints;
GoogleMap map;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

getLastLocation();
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle  savedInstanceState) {
View view = inflater.inflate(R.layout.main, container, false);
//  ...some other stuff being done here...
// Return view
return view;
}

public void getLastLocation(){
String provider = getBestProvider();
currentLocation = locationManager.getLastKnownLocation(provider);

this.markerPoints = new ArrayList<LatLng>();

LatLng fromPosition = new LatLng(currentLocation.getLatitude(),   currentLocation.getLongitude());
LatLng toPosition = new LatLng(29.633289, -82.305838);

LatLng toPosition1 = new LatLng(40.044438,-106.197281);


MainActivity.this.markerPoints.add(fromPosition);
MainActivity.this.markerPoints.add(toPosition);

// Getting URL to the Google Directions API
String url = MainActivity.this.getDirectionsUrl(fromPosition, toPosition);

DownloadTask downloadTask = new DownloadTask();

// Start downloading json data from Google Directions API
downloadTask.execute(url);

if(currentLocation != null) {
    setCurrentLocation(currentLocation);
} else { 
    // do something
}
}

public String getBestProvider() {
locationManager = (LocationManager)    getActivity().getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
criteria.setAccuracy(Criteria.NO_REQUIREMENT);
String bestProvider = locationManager.getBestProvider(criteria, true);
return bestProvider;
}

public void setCurrentLocation(Location location){
// Get current location
int currLatitude = (int) (location.getLatitude()*1E6);
int currLongitude = (int) (location.getLongitude()*1E6);
currentPoint = new GeoPoint(currLatitude,currLongitude); 
// Set current location
currentLocation = new Location("");
currentLocation.setLatitude(currentPoint.getLatitudeE6() / 1e6);
currentLocation.setLongitude(currentPoint.getLongitudeE6() / 1e6);
}

private String getDirectionsUrl(LatLng origin, LatLng dest) {
// Origin of route
String str_origin = "origin=" + origin.latitude + "," + origin.longitude;
// Destination of route
String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = str_origin + "&" + str_dest + "&" + sensor;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" +  parameters;

return url;
}

/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try
{
    URL url = new URL(strUrl);
    // Creating an http connection to communicate with url
    urlConnection = (HttpURLConnection) url.openConnection();
    // Connecting to url
    urlConnection.connect();
    // Reading data from url
    iStream = urlConnection.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
    StringBuffer sb = new StringBuffer();
    String line = "";
    while ((line = br.readLine()) != null) {
        sb.append(line);
    }

    data = sb.toString();
    br.close();
} catch (Exception e) {
    Log.d("Exception while downloading url", e.toString());
} finally {
    iStream.close();
    urlConnection.disconnect();
}
return data;
}

// Fetches data from url passed
private class DownloadTask extends AsyncTask<String, Void, ArrayList<String>> {
@Override
protected ArrayList<String> doInBackground(String... urlList) {
    try {
        ArrayList<String> returnList = new ArrayList<String>();
        for (String url : urlList) {
            // Fetching the data from web service
            String data = MainActivity.this.downloadUrl(url);
            returnList.add(data);
        }
        return returnList;
    } catch (Exception e) {
        Log.d("Background Task", e.toString());
        return null; // Failed, return null
    }
}

// Executes in UI thread, after the execution of
// doInBackground()
@Override
protected void onPostExecute(ArrayList<String> results) {
    super.onPostExecute(results);

    ParserTask parserTask = new ParserTask();

    for (String url : results) {
        parserTask.execute(url);
    }

    // Invokes the thread for parsing the JSON data
    // parserTask.execute(results);
}
}

/** A class to parse the Google Places in JSON format */
private class ParserTask extends AsyncTask<String, Integer,    ArrayList<List<HashMap<String, String>>>> {
// Parsing the data in non-ui thread
@Override
protected ArrayList<List<HashMap<String, String>>> doInBackground(String... jsonData) {
    try {
        ArrayList<List<HashMap<String, String>>> routes = new  ArrayList<List<HashMap<String, String>>>();

        // for (String url : jsonData) {
        for (int i = 0; i < jsonData.length; i++) {
            JSONObject jObject = new JSONObject(jsonData[i]);

            DirectionsJSONParser parser = new DirectionsJSONParser();
            // Starts parsing data
            routes = (ArrayList<List<HashMap<String, String>>>) parser.parse(jObject);
        }
        return routes;
    } catch (Exception e) {
        Log.d("Background task", e.toString());
        return null; // Failed, return null
    }
}

// Executes in UI thread, after the parsing process
@Override
protected void onPostExecute(List<List<HashMap<String, String>>> result)  
{
    if (result.size() < 1) 
    {
        Toast.makeText(getActivity(), "No Points", Toast.LENGTH_SHORT).show();
        return;
    }

    TextView tv1 = (TextView) getActivity().findViewById(R.id.location1);
    TextView tv2 = (TextView) getActivity().findViewById(R.id.location2);
    TextView tv3 = (TextView) getActivity().findViewById(R.id.location3);
    TextView tv4 = (TextView) getActivity().findViewById(R.id.location4);

    TextView[] views = {tv1, tv2, tv3, tv4};


    // Traversing through all the routes
    for (int i = 0; i < result.size(); i++) 
    {
        // Fetching i-th route
        List<HashMap<String, String>> path = result.get(i);
        String distance = "No distance";

        // Fetching all the points in i-th route
        for (int j = 0; j < path.size(); j++) 
        {
            HashMap<String, String> point = path.get(j);

            if (j == 0)  
            {
                distance = point.get("distance");
                continue;
            }
        }

        // Set text
        views[i].setText(distance);
    }
}
}
}

main.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" >

<fragment
    android:name="com.google.android.gms.maps.SupportMapFragment"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    android:id="@+id/map"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
</LinearLayout>
sree7k7
  • 17
  • 9

3 Answers3

0

This is a common problem with Google Maps, lots of people ask this and researching shows so many subjective questions... Try this:

  1. Check you have enabled the Google Maps Android API v2 Service on your Google API Console. If you have NOT, then enable it, then recreate the API key by pressing the Generate new key.

  2. Double and triple check all the required permissions and the API key you have copy and pasted.

  3. Uninstall the app on your device or AVD and reinstall again and try... sometimes it needs a complete refresh.

Go to particular Location using LatLng

Here is an easy to use method I designed to go to a particular location. Put this inside your Activity or make a new Class and simply pass the data to it :)

/** goToLocation
 * @param map - You GoogleMap reference
 * @param location - your LatLng value
 * @param zoom Float - ie. 15
 * @param b Boolean - Animate camera movement: true or false
 */
public void goToLocation(GoogleMap map, LatLng ll, float zoom, boolean b) {
    if (b == true) {
        map.animateCamera(CameraUpdateFactory.newLatLngZoom(ll, zoom));
    } else {
        map.moveCamera(CameraUpdateFactory.newLatLngZoom(ll, zoom));
    }
}
KickAss
  • 4,210
  • 8
  • 33
  • 41
  • I did copy of your code and pasted in activity. but i couldn't navigate to particular location. – sree7k7 Aug 31 '13 at 15:23
  • Was there any Errors? Post your entire Activity code in your main post above so I can take a look :) – KickAss Aug 31 '13 at 15:27
0

In your manifest you have mentioned this. uses-library android:name="com.google.android.maps" Remove that. It's old version ie google map v1

and check your key whether you are using debug or release key.

Release key procedure are here

Google Map Android API v2 can't display map in play store application

Community
  • 1
  • 1
Shadow
  • 6,864
  • 6
  • 44
  • 93
  • Thanks for your reply. It works...:) I would like to navigate to a particular location by using latitude and longitude values. can I have some suggestions please. – sree7k7 Aug 31 '13 at 12:19
0

See my Edited answer for the Go to particular Location question.

KickAss
  • 4,210
  • 8
  • 33
  • 41