我正在开发一款Android谷歌地图应用。如何创建当前位置,气球覆盖和其他标记位置点。
我正在(CustomMap.java)
中创建其他标记位置点这里我也想要当前位置。请帮帮我
CustomMap.java
public class CustomMap extends MapActivity implements LocationListener {
MapView mapView;
List<Overlay> mapOverlays;
Drawable drawable;
Drawable drawable2;
CustomItemizedOverlay<CustomOverlayItem> itemizedOverlay;
CustomItemizedOverlay<CustomOverlayItem> itemizedOverlay2;
double longitude;
double latitude;
long start;
long stop;
int x, y;
int lati = 0;
int longit = 0;
GeoPoint touchedPoint;
public boolean overlay_status=false;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// making it full screen
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_custom_map);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mapOverlays = mapView.getOverlays();
// first overlay
drawable = getResources().getDrawable(R.drawable.marker);
itemizedOverlay = new CustomItemizedOverlay<CustomOverlayItem>(drawable, mapView);
//first overlay in first pinpoint
GeoPoint point = new GeoPoint((int)(13.0094444*1E6),(int)(77.5508333*1E6));
CustomOverlayItem overlayItem = new CustomOverlayItem(point, "ISKCON Temple Bangalore(1997)",
"(ISKCON Temple, Chord Rd, Mahalakshmipuram Layout, Nagapura, Bangalore, Karnataka, India)",
"http://www.iskcon-bda.org/data/HKH.jpg");
itemizedOverlay.addOverlay(overlayItem);
//first overlay in second pinpoint
GeoPoint point2 = new GeoPoint((int)(12.8008*1E6),(int)(77.5756*1E6));
CustomOverlayItem overlayItem2 = new CustomOverlayItem(point2, "Bannerghatta National Park",
"(Bannerghatta Biological Park is carved out of the Bannerghatta National Park in the year 2002)",
"http://www.google.co.in/imgres?imgurl=http://travel.sulekha.com/" +
"india/karnataka/bangalore/photos/bannerghatta-national-park-25.jpg&imgrefurl=http://travel.sulekha.com/" +
"a-visit-to-bannerghatta-national-park_bangalore-travelogue-3541.htm&h=194&w=259&sz=1&tbnid=K5TNPwXHgihgRM:&tbnh=" +
"119&tbnw=160&zoom=1&usg=__MFNGL1C2InXP7jw7XmEi4ym45NY=&docid=d78iF3T5ditWeM&itg=1&hl=en&sa=X&ei=" +
"CpwQUdOmHIPUrQe0m4H4Bg&sqi=2&ved=0CHwQ_B0wCw");
itemizedOverlay.addOverlay(overlayItem2);
mapOverlays.add(itemizedOverlay);
// second overlay
drawable2 = getResources().getDrawable(R.drawable.marker2);
itemizedOverlay2 = new CustomItemizedOverlay<CustomOverlayItem>(drawable2, mapView);
//second overlay in third pinpoint
GeoPoint point3 = new GeoPoint((int)(12.8339956*1E6),(int)(77.4009816*1E6));
CustomOverlayItem overlayItem3 = new CustomOverlayItem(point3, "Wonderla Bangalore(2005)",
"(Wonderla is an amusement park located near Bidadi, 28 kilometres Bangalore, spanning 82 acres of land)",
"http://www.google.co.in/imgres?imgurl=http://www.yohyoh.com/places-tourism/pictures/wb3.jpg&imgrefurl=http://" +
"www.yohyoh.com/places-tourism/view.php/popular-tours/Karnataka/Bangalore/wonderla-bangalore/561/8192987807&h=" +
"194&w=259&sz=1&tbnid=RoLC5gzRHP6VSM:&tbnh=160&tbnw=213&zoom=1&usg=__ShDQAmQ0zjQaKbsy0A63BokHAmk=" +
"&docid=J1aN09WXjvHw4M&itg=1&hl=en&sa=X&ei=Sp0QUbvIEMHjrAfTy4GgBA&ved=0CNMBEPwdMAo");
itemizedOverlay2.addOverlay(overlayItem3);
//second overlay in third pinpoint
GeoPoint point4 = new GeoPoint((int)(12.8385923*1E6),(int)(77.661710599*1E6));
CustomOverlayItem overlayItem4 = new CustomOverlayItem(point4, "Wipro Technologies,Bangalore",
"(Wipro Technologies, Electronics City Phase 1, Electronics City, Bangalore, Karnataka 560100, India)",
"http://www.electronic-city.in/companies/profile/wipro/wipro-electronic-city.jpg");
itemizedOverlay2.addOverlay(overlayItem4);
mapOverlays.add(itemizedOverlay2);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
String address = "";
Geocoder geoCoder = new Geocoder(
getBaseContext(), Locale.getDefault());
latitude = location.getLatitude();
// Getting longitude
longitude = location.getLongitude();
// Creating an instance of GeoPoint corresponding to latitude and longitude
GeoPoint point5 = new GeoPoint((int)(latitude * 1E6), (int)(longitude*1E6));
try {
List<Address> addresses = geoCoder.getFromLocation(
point.getLatitudeE6() / 1E6,
point.getLongitudeE6() / 1E6, 1);
if (addresses.size() > 0) {
for (int index = 0; index < addresses.get(0).getMaxAddressLineIndex(); index++)
address += addresses.get(0).getAddressLine(index) + " ";
}
tvLocation.setText("Address :" + address );
}
catch (IOException e) {
e.printStackTrace();
}
drawable = getResources().getDrawable(R.drawable.url);
itemizedOverlay = new CustomItemizedOverlay<CustomOverlayItem>(drawable, mapView);
mapView.getOverlays().add(itemizedOverlay);
itemizedOverlay.runOnFirstFix(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
mapView.getOverlays().add(itemizedOverlay);
}
});
MapController mapController = mapView.getController();
// Locating the Geographical point in the Map
mapController.animateTo(point5);
itemizedOverlay.enableMyLocation();
mapView.postInvalidate();
// Getting list of overlays available in the map
List<Overlay> mapOverlays = mapView.getOverlays();
CustomOverlayItem currentLocation = new CustomOverlayItem(point, "Current Location", "Latitude : " + latitude + ", Longitude:" + longitude, null);
// Adding the mark to the overlay
itemizedOverlay.addOverlay(currentLocation);
// Clear Existing overlays in the map
mapOverlays.clear();
mapOverlays.add(itemizedOverlay);
if (savedInstanceState == null) {
//Contains Displaying the pinpoint
final MapController mc = mapView.getController();
mc.animateTo(point);
mc.setZoom(16);
}else {
// example restoring focused state of overlays
int focused;
focused = savedInstanceState.getInt("focused_1", -1);
if (focused >= 0) {
itemizedOverlay.setFocus(itemizedOverlay.getItem(focused));
}
focused = savedInstanceState.getInt("focused_2", -1);
if (focused >= 0) {
itemizedOverlay2.setFocus(itemizedOverlay2.getItem(focused));
}
}
Touchy t = new Touchy();
mapOverlays = mapView.getOverlays();
mapOverlays.add(t);
}
@Override
protected boolean isRouteDisplayed() {
return false;
}
@Override
protected void onSaveInstanceState(Bundle outState) {
// example saving focused state of overlays
if (itemizedOverlay.getFocus() != null) outState.putInt("focused_1", itemizedOverlay.getLastFocusedIndex());
if (itemizedOverlay2.getFocus() != null) outState.putInt("focused_2", itemizedOverlay2.getLastFocusedIndex());
super.onSaveInstanceState(outState);
}
//Contains creating the option menu items
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, 0, 1, "Remove Overlay");
menu.add(0, 1, 1, "set Overlay");
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.drawable.home_menu, menu);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
if(overlay_status==false)
{
menu.findItem(1).setVisible(false);
menu.findItem(0).setVisible(true);
//overlay_status=true;
}
else
{
menu.findItem(0).setVisible(false);
menu.findItem(1).setVisible(true);
// overlay_status=false;
}
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.home1:
finish();
return true;
case 0:
//Toast.makeText(getApplicationContext(), "remove overlay ", Toast.LENGTH_SHORT).show();
// example hiding balloon before removing overlay
if (itemizedOverlay.getFocus() != null) {
itemizedOverlay.hideBalloon();
}
mapOverlays.remove(itemizedOverlay);
mapView.invalidate();
overlay_status=true;
return true;
case 1:
Toast.makeText(getApplicationContext(), "set overlay ", Toast.LENGTH_SHORT).show();
if (itemizedOverlay.getFocus() != null) {
itemizedOverlay.getBalloonBottomOffset();
}
mapOverlays.add(itemizedOverlay);
mapView.bringToFront();
overlay_status=false;
return true;
default:
return super.onOptionsItemSelected(item);
}
}
class Touchy extends Overlay{
List<Address> address;
String display = "";
String display1;
@SuppressWarnings({ "deprecation" })
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 = mapView.getProjection().fromPixels(x, y);
Geocoder geocoder = new Geocoder(getBaseContext(), Locale.getDefault());
try{
address = geocoder.getFromLocation(touchedPoint.getLatitudeE6() / 1E6, touchedPoint.getLongitudeE6() / 1E6, 1);
if(address.size() > 0){
for(int i = 0; i<address.get(0).getMaxAddressLineIndex(); i++){
display +=address.get(0).getAddressLine(i) + "\n";
}
Toast.makeText(getBaseContext(), display, Toast.LENGTH_LONG).show();
}
}catch(IOException e1){
}
finally
{
display1=display;
display=" ";
}
}
if(e.getAction() == MotionEvent.ACTION_UP){
stop = e.getEventTime();
}
/**contains the creating a Alert Dialog Box (place apinpoint, get address, Toggle View)
* In Dialog Box Maximum three buttens
*/
if(stop - start > 1000){
AlertDialog alert = new AlertDialog.Builder(CustomMap.this).create();
alert.setTitle("pick an Option");
alert.setMessage("I told to pick an option");
alert.setButton("place a pinpoint", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
CustomOverlayItem overlayItem = new CustomOverlayItem(touchedPoint,"Address:",display1, display1);
// SimpleItemizedOverlay itemizedOverlay = new SimpleItemizedOverlay(drawable, mapView);
CustomItemizedOverlay<CustomOverlayItem> itemOverlay = new CustomItemizedOverlay<CustomOverlayItem>(drawable, mapView);
// CustomPinpoint custom = new CustomPinpoint(drawable, CustomMap.this);
// custom.insertPinpoint(overlayItem);
itemOverlay.insertPinpoint(overlayItem);
itemOverlay.addOverlay(overlayItem);
mapOverlays.add(itemOverlay);
}
});
alert.setButton2("get address", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
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.makeText(getBaseContext(), display, Toast.LENGTH_LONG).show();
}
}catch(IOException e){
}
}
});
alert.setButton3("Toggle View", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if(mapView.isSatellite()){
mapView.setSatellite(false);
mapView.setStreetView(true);
}else{
mapView.setStreetView(false);
mapView.setSatellite(true);
}
}
});
alert.show();
return true;
}
return false;
}
}
@Override
public void onLocationChanged(Location location) {
lati = (int) (location.getLatitude() * 1E6);
longit = (int) (location.getLongitude() * 1E6);
GeoPoint ourLocation = new GeoPoint(lati, longit);
OverlayItem overlayItem = new OverlayItem(ourLocation, "What's up?", "2nd String");
CustomPinpoint custom = new CustomPinpoint(drawable, CustomMap.this);
custom.insertPinpoint(overlayItem);
mapOverlays.add(custom);
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
答案 0 :(得分:3)
试试这个AndroidHive Google代码
Google地图链接Android Working with Google Places and Maps Tutorial
public class SinglePlaceActivity extends Activity {
// flag for Internet connection status
Boolean isInternetPresent = false;
// Connection detector class
ConnectionDetector cd;
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
// Google Places
GooglePlaces googlePlaces;
// Place Details
PlaceDetails placeDetails;
// Progress dialog
ProgressDialog pDialog;
// KEY Strings
public static String KEY_REFERENCE = "reference"; // id of the place
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.single_place);
Intent i = getIntent();
// Place referece id
String reference = i.getStringExtra(KEY_REFERENCE);
// Calling a Async Background thread
new LoadSinglePlaceDetails().execute(reference);
}
/**
* Background Async Task to Load Google places
* */
class LoadSinglePlaceDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SinglePlaceActivity.this);
pDialog.setMessage("Loading profile ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Profile JSON
* */
protected String doInBackground(String... args) {
String reference = args[0];
// creating Places class object
googlePlaces = new GooglePlaces();
// Check if used is connected to Internet
try {
placeDetails = googlePlaces.getPlaceDetails(reference);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed Places into LISTVIEW
* */
if(placeDetails != null){
String status = placeDetails.status;
// check place deatils status
// Check for all possible status
if(status.equals("OK")){
if (placeDetails.result != null) {
String name = placeDetails.result.name;
String address = placeDetails.result.formatted_address;
String phone = placeDetails.result.formatted_phone_number;
String latitude = Double.toString(placeDetails.result.geometry.location.lat);
String longitude = Double.toString(placeDetails.result.geometry.location.lng);
Log.d("Place ", name + address + phone + latitude + longitude);
// Displaying all the details in the view
// single_place.xml
TextView lbl_name = (TextView) findViewById(R.id.name);
TextView lbl_address = (TextView) findViewById(R.id.address);
TextView lbl_phone = (TextView) findViewById(R.id.phone);
TextView lbl_location = (TextView) findViewById(R.id.location);
// Check for null data from google
// Sometimes place details might missing
name = name == null ? "Not present" : name; // if name is null display as "Not present"
address = address == null ? "Not present" : address;
phone = phone == null ? "Not present" : phone;
latitude = latitude == null ? "Not present" : latitude;
longitude = longitude == null ? "Not present" : longitude;
lbl_name.setText(name);
lbl_address.setText(address);
lbl_phone.setText(Html.fromHtml("<b>Phone:</b> " + phone));
lbl_location.setText(Html.fromHtml("<b>Latitude:</b> " + latitude + ", <b>Longitude:</b> " + longitude));
}
}
else if(status.equals("ZERO_RESULTS")){
alert.showAlertDialog(SinglePlaceActivity.this, "Near Places",
"Sorry no place found.",
false);
}
else if(status.equals("UNKNOWN_ERROR"))
{
alert.showAlertDialog(SinglePlaceActivity.this, "Places Error",
"Sorry unknown error occured.",
false);
}
else if(status.equals("OVER_QUERY_LIMIT"))
{
alert.showAlertDialog(SinglePlaceActivity.this, "Places Error",
"Sorry query limit to google places is reached",
false);
}
else if(status.equals("REQUEST_DENIED"))
{
alert.showAlertDialog(SinglePlaceActivity.this, "Places Error",
"Sorry error occured. Request is denied",
false);
}
else if(status.equals("INVALID_REQUEST"))
{
alert.showAlertDialog(SinglePlaceActivity.this, "Places Error",
"Sorry error occured. Invalid Request",
false);
}
else
{
alert.showAlertDialog(SinglePlaceActivity.this, "Places Error",
"Sorry error occured.",
false);
}
}else{
alert.showAlertDialog(SinglePlaceActivity.this, "Places Error",
"Sorry error occured.",
false);
}
}
});
}
}
}
答案 1 :(得分:0)
试试这个,
mapView.getOverlays().add(locationoverlay);
locationoverlay.runOnFirstFix(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
mapView.getOverlays().add(locationoverlay);
}
});
locationoverlay.enableMyLocation();
mapView.postInvalidate();
上面的代码将提供android默认标记叠加层中的当前位置