Skip to content

Instantly share code, notes, and snippets.

@ChrisRisner
Created September 14, 2012 21:56
Show Gist options
  • Save ChrisRisner/3725162 to your computer and use it in GitHub Desktop.
Save ChrisRisner/3725162 to your computer and use it in GitHub Desktop.
GeoDemo-Android-1
public class Constants {
public static final String kFindPOIUrl = "http://yoursubdomain.azurewebsites.net/api/Location/FindPointsOfInterestWithinRadius";
}
import java.util.ArrayList;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.util.Log;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapView;
import com.google.android.maps.OverlayItem;
public class GeoItemizedOverlay extends ItemizedOverlay<OverlayItem> {
private final String TAG = "GeoItemizedOverlay";
private Context mContext;
public GeoItemizedOverlay(Drawable defaultMarker, Context context) {
super(boundCenterBottom(defaultMarker));
this.mContext = context;
this.populate();
}
private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
public void addOverlay(OverlayItem overlay) {
mOverlays.add(overlay);
populate();
}
@Override
protected OverlayItem createItem(int i) {
return mOverlays.get(i);
}
@Override
public int size() {
return mOverlays.size();
}
@Override
public boolean onTap(GeoPoint p, MapView mapView) {
Log.i(TAG, "item tapped: " + p.toString());
return super.onTap(p, mapView);
}
/***
* When an overlay item is tapped, pop up an alert with it's Title and
* snippet
*/
@Override
protected boolean onTap(int index) {
Log.i(TAG, "Index of tapped item: " + index);
OverlayItem tappedItem = mOverlays.get(index);
Log.i(TAG, "Title of tapped item: " + tappedItem.getTitle());
Log.i(TAG, "shippet of tapped item: " + tappedItem.getSnippet());
// Bulid the alert dialog and show it
AlertDialog dialog = new AlertDialog.Builder(this.mContext).create();
dialog.setTitle(tappedItem.getTitle());
dialog.setMessage(tappedItem.getSnippet());
final String url = tappedItem.getSnippet();
//When the user clicks view image, open a browser with the image URL
dialog.setButton("View Image", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent webIntent = new Intent(Intent.ACTION_VIEW);
webIntent.setData(Uri.parse(url));
mContext.startActivity(webIntent);
}
});
dialog.setButton2("Close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
dialog.show();
return super.onTap(index);
}
}
private void loadPointsFromServer(Location location) {
try {
String fetchUrl = Constants.kFindPOIUrl + "?latitude="
+ location.getLatitude() + "&longitude="
+ location.getLongitude() + "&radiusInMeters=1000";
URL url = new URL(fetchUrl);
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
try {
InputStream in = new BufferedInputStream(
urlConnection.getInputStream());
BufferedReader r = new BufferedReader(new InputStreamReader(in));
StringBuilder stringBuilderResult = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
stringBuilderResult.append(line);
}
JSONArray jsonArray = new JSONArray(
stringBuilderResult.toString());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Double latitude = jsonObject.getDouble("Latitude");
Double longitude = jsonObject.getDouble("Longitude");
String description = jsonObject.getString("Description");
String itemUrl = jsonObject.getString("Url");
// The item URL comes back with quotes at the beginning,
// so we strip them out
itemUrl = itemUrl.replace("\"", "");
// Create a new geo point with this information and add it
// to the overlay
GeoPoint point = coordinatesToGeoPoint(new double[] {
latitude, longitude });
OverlayItem overlayitem = new OverlayItem(point,
description, itemUrl);
mItemizedOverlay.addOverlay(overlayitem);
}
} catch (Exception ex) {
Log.e("MainActivity", "Error getting data from server: " + ex.getMessage());
} finally {
urlConnection.disconnect();
}
} catch (Exception ex) {
Log.e("MainActivity", "Error creating connection: " + ex.getMessage());
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get UI controls
mLblLatitudeValue = (TextView) findViewById(R.id.lblLatitudeValue);
mLblLongitudeValue = (TextView) findViewById(R.id.lblLongitudeValue);
mMapMain = (MapView) findViewById(R.id.mapMain);
mMapMain.setBuiltInZoomControls(true);
mMapOverlays = mMapMain.getOverlays();
mDrawable = this.getResources().getDrawable(R.drawable.androidmarker);
mItemizedOverlay = new GeoItemizedOverlay(mDrawable, this);
mMapOverlays.add(mItemizedOverlay);
MyLocationOverlay myLocationOverlay = new MyLocationOverlay(this,
mMapMain);
mMapMain.getOverlays().add(myLocationOverlay);
myLocationOverlay.enableMyLocation();
// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location
// provider.
makeUseOfNewLocation(location);
}
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
};
// Register the listener with the Location Manager to receive location
// updates
boolean couldPollNetworkProvider = true;
boolean couldPollGPSProvider = true;
try {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
} catch (Exception ex) {
couldPollNetworkProvider = false;
}
try {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0, locationListener);
} catch (Exception ex) {
couldPollGPSProvider = false;
}
if (!couldPollGPSProvider && !couldPollNetworkProvider)
Toast.makeText(this, "Couldn't get any location provider",Toast.LENGTH_LONG).show();
else if (!couldPollGPSProvider)
Toast.makeText(this, "Couldn't get GPS provider",Toast.LENGTH_LONG).show();
else if (!couldPollNetworkProvider)
Toast.makeText(this, "Couldn't get network provider",Toast.LENGTH_LONG).show();
protected void makeUseOfNewLocation(Location location) {
// Set our text views to the new long and lat
mLblLatitudeValue.setText(String.valueOf(location.getLatitude()));
mLblLongitudeValue.setText(String.valueOf(location.getLongitude()));
GeoPoint point = coordinatesToGeoPoint(new double[] {
location.getLatitude(), location.getLongitude() });
CenterLocation(point);
// Get Data from server
loadPointsFromServer(location);
mMapMain.invalidate();
}
public static GeoPoint coordinatesToGeoPoint(double[] coords) {
if (coords.length > 2) {
return null;
}
if (coords[0] == Double.NaN || coords[1] == Double.NaN) {
return null;
}
final int latitude = (int) (coords[0] * 1E6);
final int longitude = (int) (coords[1] * 1E6);
return new GeoPoint(latitude, longitude);
}
private void CenterLocation(GeoPoint centerGeoPoint) {
mMapMain.getController().animateTo(centerGeoPoint);
};
private MapView mMapMain;
private TextView mLblLatitudeValue;
private TextView mLblLongitudeValue;
private List<Overlay> mMapOverlays;
private Drawable mDrawable;
private GeoItemizedOverlay mItemizedOverlay;
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="@+id/linearLayoutLongitude"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/lblLongitudeHeader"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Longitude" />
<TextView
android:id="@+id/lblLongitudeValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayoutLatitude"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/lblLatitudeHeader"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Latitude" />
<TextView
android:id="@+id/lblLatitudeValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<com.google.android.maps.MapView
android:id="@+id/mapMain"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:apiKey="ENTER YOUR API KEY"
android:clickable="true" />
</RelativeLayout>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment