Hello开发人员,
我在android studio中使用谷歌地图活动创建了一个地图,我的类扩展了AppCompactActivity,因为我想使用工具栏。当运行onMapReady时调用两次(我使用Log.d尝试)但是当我将AppCompactActivity更改为FragmentActivity时它只调用一次。
更新代码:
public class Maps extends AppCompatActivity implements OnMapReadyCallback, DatePickerDialog.OnDateSetListener, View.OnCreateContextMenuListener {
Context context;
private GoogleMap mMap;
private LocationManager locationManager;
Location location;
TextView eta, distance, tvfrom, tvto;
EditText txtTruck;
AutoCompleteTextView search;
Bitmap keraniMarker, truck, arrowup, puninar;
BitmapDescriptor bdfKerani = null, bdfTruck = null, bdfArrow = null, bdfPuninar = null;
CardView cardFind;
Button btnfind;
SwitchCompat swTraffic;
/////////////////////
static SwitchCompat swProgress;
TextView tvFilter;
ListView lvOrderTruck;
EditText txtSearch;
ArrayList<Order_Truck_SetGet> complete = new ArrayList<>();
ArrayList<Order_Truck_SetGet> onGoing = new ArrayList<>();
String custCode = "nocust";
static String nopol_to_map = "all";
private Order_Truck_Adapter adapter_order_truck;
////////////////////
ArrayList<String> nop = new ArrayList<>();
ArrayList<LastLocationSetterGetter> lastloc = new ArrayList<>();
ArrayList<LatLng> livelatlng = new ArrayList<>();
ArrayList<startmark> arstart = new ArrayList<>();
ArrayList<String> project = new ArrayList<>();
String lokasi, nama, time, speed, statustitle;
TextView namadet, lokasidet, timedet, txtspeed, txtSPK, txtOMpils, txtOMccms, txtCust, txtDriver, txtRute, tvSiMbl, txtSiMbl;
ImageView call, sms, wa;
String telp = "+6281280688872";
LinearLayout llSpk, llOMpils, llOMccms, llCust, llDriver, llRute, llSiMbl;
private ProgressDialog pDialog;
private Dialog dashDialog, listOrderDialog;
int FLAG_START_DATE = 0;
int FLAG_END_DATE = 1;
int flag = -1;
int flag_menu = 0;
private long mLastClickTime = 0;
static final int LOCATION = 1;
static final int WRITE_EXTERNAL = 2;
static final int CALL_PHONE = 3;
static final int SEND_SMS = 4;
int PERMISSION_ALL = 1;
Marker lastmark = null;
Marker startmark = null;
Marker track_arrow = null;
String pilih = Order_Truck.nopol_to_map;
String projectselect = "all";
LinearLayout llnopol, lldate, lllokasi;
ImageView nopol_arrow, date_arrow, lokasi_arrow;
ListView lvTruck;
ArrayList<Dashboard_Truck_SetGet> dastruck = new ArrayList<>();
private Dashboard_Truck_adapter adapter;
private DisplayMetrics metrics;
private boolean mAscendingOrder[] = {true, true, true};
String classname = this.getClass().getSimpleName();
Thread live = new Thread();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
//set for check permission
String[] PERMISSIONS = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CALL_PHONE, Manifest.permission.SEND_SMS};
if (!hasPermissions(this, PERMISSIONS)) {
ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
}
distance = (TextView) findViewById(R.id.DISTANCE);
eta = (TextView) findViewById(R.id.ETA);
search = (AutoCompleteTextView) findViewById(R.id.search);
cardFind = (CardView) findViewById(R.id.cardFind);
tvfrom = (TextView) findViewById(R.id.txtFrom);
tvto = (TextView) findViewById(R.id.txtTo);
btnfind = (Button) findViewById(R.id.btnFind);
swTraffic = (SwitchCompat) findViewById(R.id.swTraffic);
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
pDialog = new ProgressDialog(this);
pDialog.setMessage("Authenticating...");
pDialog.setCancelable(false);
cekOverlay();
project.add("All Project");
project.add("EXIM");
//set logo for marker
//option 1
BitmapDrawable bitmap_kerani = (BitmapDrawable) getResources().getDrawable(R.drawable.truck);
Bitmap kerani_ico = bitmap_kerani.getBitmap();
keraniMarker = Bitmap.createScaledBitmap(kerani_ico, 100, 100, false);
bdfKerani = BitmapDescriptorFactory.fromBitmap(keraniMarker);
BitmapDrawable bitmap_puninar = (BitmapDrawable) getResources().getDrawable(R.drawable.marker_puninar);
Bitmap puninar_ico = bitmap_puninar.getBitmap();
puninar = Bitmap.createScaledBitmap(puninar_ico, 150, 150, false);
bdfPuninar = BitmapDescriptorFactory.fromBitmap(puninar);
BitmapDrawable bitmap_truck = (BitmapDrawable) getResources().getDrawable(R.drawable.flat_truck);
Bitmap truck_icon = bitmap_truck.getBitmap();
truck = Bitmap.createScaledBitmap(truck_icon, 70, 100, false);
bdfTruck = BitmapDescriptorFactory.fromBitmap(truck);
BitmapDrawable bitmap_arrow = (BitmapDrawable) getResources().getDrawable(R.drawable.green_arrow);
Bitmap arrow_up = bitmap_arrow.getBitmap();
arrowup = Bitmap.createScaledBitmap(arrow_up, 70, 50, false);
bdfArrow = BitmapDescriptorFactory.fromBitmap(arrowup);
tvfrom.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setDate();
flag = FLAG_START_DATE;
}
});
tvto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setDate();
flag = FLAG_END_DATE;
}
});
btnfind.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (tvfrom.getText().length() == 0) {
Toast.makeText(getApplicationContext(), "From date must be filled", Toast.LENGTH_SHORT).show();
} else if (tvto.getText().length() == 0) {
Toast.makeText(getApplicationContext(), "To date must be filled", Toast.LENGTH_SHORT).show();
} else if (pilih.isEmpty()) {
Toast.makeText(getApplicationContext(), "Police number must be choosen", Toast.LENGTH_SHORT).show();
} else {
getcarloc(pilih, projectselect);
}
}
});
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.getUiSettings().setCompassEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setRotateGesturesEnabled(true);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(-3.503399, 112.423781), 4.0f));
swTraffic.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
swTraffic.setText("Traffic ON ");
mMap.setTrafficEnabled(true);
} else {
mMap.setTrafficEnabled(false);
swTraffic.setText("Traffic OFF ");
}
}
});
//GPS LAST POSITION
search.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
search.setText("");
}
});
Log.d("pilihan", pilih + " ^.^");
getNopol(projectselect);
getcarloc(pilih, projectselect);
mMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {
@Override
public boolean onMyLocationButtonClick() {
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 15.0f));
return false;
}
});
}
public void getcarloc(final String nopol, final String project) {
if (flag_menu != 2) {
mMap.clear();
livelatlng.clear();
lastloc.clear();
}
Log.d("PILIH2", nopol);
Log.d("LIVESTATUS", String.valueOf(live.getState()));
String url;
showpDialog();
if (flag_menu == 1) {
url = Config.GET_LOCATION_HISTORICAL;
} else {
url = Config.GET_LAST_LOCATION;
}
mMap.addMarker(new MarkerOptions().position(new LatLng(-6.172172, 106.941581)).title("Puninar Jaya Cakung").snippet("Puninar Jaya Cakung").icon(bdfPuninar));
mMap.addMarker(new MarkerOptions().position(new LatLng(-6.128611, 106.941747)).title("Puninar Jaya Nagrak").snippet("Puninar Jaya Nagrak").icon(bdfPuninar));
mMap.addMarker(new MarkerOptions().position(new LatLng(-6.029199, 106.085906)).title("Puninar Jaya Cilegon").snippet("Puninar Jaya Cilegon").icon(bdfPuninar));
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d("response", response);
hidepDialog();
try {
JSONObject json = new JSONObject(response);
JSONArray jsonArray = json.getJSONArray("data");
if (String.valueOf(jsonArray).equals("[]")) {
hidepDialog();
if (flag_menu == 1) {
Toast.makeText(getApplicationContext(), "There is No Trip History From " + tvfrom.getText() + " Until " + tvto.getText() + " for " + pilih, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "There is No Data / Location For " + pilih, Toast.LENGTH_SHORT).show();
}
} else {
Log.e("JSONARRAY", String.valueOf(jsonArray));
String vehicle_id = null,
vehicle_number = null;
for (int i = 0; i < jsonArray.length(); i++) {
//Get data last location or live tracking
JSONObject obj = jsonArray.getJSONObject(i);
String position_id = obj.getString("position_id");
if (flag_menu != 1) {
vehicle_id = obj.getString("vehicle_id");
vehicle_number = obj.getString("vehicle_number");
}
String date_time = obj.getString("date_time");
Double longitude = Double.parseDouble(obj.getString("longitude")) / 10000000;
Double latitude = Double.parseDouble(obj.getString("latitude")) / 10000000;
String speed = obj.getString("speed");
String course = obj.getString("course");
String street_name = obj.getString("street_name");
String kecamatan = obj.getString("kecamatan");
String kabupaten = obj.getString("kabupaten");
if (flag_menu != 1) {
lastloc.add(new LastLocationSetterGetter(position_id, vehicle_id, vehicle_number,
date_time, longitude, latitude, speed, course, street_name, kecamatan, kabupaten));
} else {
lastloc.add(new LastLocationSetterGetter(position_id, pilih,
date_time, longitude, latitude, speed, course, street_name, kecamatan, kabupaten));
}
LatLng latLng = new LatLng(latitude, longitude);
if (lastmark != null) {
lastmark.remove();
}
//Log.i("InfoSize", String.valueOf(lastloc.size()));
//create marker for live tracking
if (flag_menu != 0) {
livelatlng.add(latLng);
if (startmark == null) {
//create start marker
startmark = mMap.addMarker(new MarkerOptions().position(latLng).title("Start").snippet(vehicle_number).icon(bdfKerani));
arstart.add(new startmark(street_name, kecamatan, kabupaten, vehicle_number, date_time, speed));
} else {
// create live tracking marker
lastmark = mMap.addMarker(new MarkerOptions().position(latLng).title(pilih).snippet(vehicle_number).icon(bdfTruck));
lastmark.setFlat(true);
lastmark.setRotation(Float.parseFloat(course));
if (lastloc.size() > 2) {
track_arrow = mMap.addMarker(new MarkerOptions()
.position(new LatLng(lastloc.get(lastloc.size() - 2).getLatitude(), lastloc.get(lastloc.size() - 2).getLongitude()))
.title(lastloc.get(lastloc.size() - 2).getPosition_id())
.snippet(lastloc.get(lastloc.size() - 2).getVehicle_number())
.icon(bdfArrow));
track_arrow.setFlat(true);
track_arrow.setRotation(Float.parseFloat(lastloc.get(lastloc.size() - 2).getCourse()));
}
}
if (livelatlng.size() > 1) {
//int ap22 = getResources().getColor(R.color.fbutton_color_wet_asphalt);
int ap23 = ContextCompat.getColor(getApplicationContext(), R.color.fbutton_color_belize_hole);
Polyline line = mMap.addPolyline(new PolylineOptions()
.add(livelatlng.get(livelatlng.size() - 2), livelatlng.get(livelatlng.size() - 1))
.width(10)
.color(ap23));
}
} else {
//create marker for last location
MarkerOptions marker = new MarkerOptions().position(latLng).title(vehicle_number).snippet(vehicle_number).icon(bdfKerani);
mMap.addMarker(marker);
}
}
Log.d("TOTALRECORD", String.valueOf(livelatlng.size()));
if (nopol != "all") {
Log.e("lastloc", String.valueOf(lastloc.size()));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lastloc.get(lastloc.size() - 1).getLatitude(), lastloc.get(lastloc.size() - 1).getLongitude()), 16.0f));
//cardFind.setVisibility(View.VISIBLE);
} else {
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(-4.979218, 107.950524), 5.0f));
}
clickmap();
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("ERRORCATCH", String.valueOf(e));
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
hidepDialog();
Log.e("ERROR", String.valueOf(error));
String message = null;
if (error instanceof NetworkError) {
message = "Cannot connect to Internet...Please check your connection!";
} else if (error instanceof ServerError) {
message = "The server could not be found. Please try again after some time!!";
} else if (error instanceof AuthFailureError) {
message = "Cannot connect to Internet...Please check your connection!";
} else if (error instanceof ParseError) {
message = "Parsing error! Please try again after some time!!";
} else if (error instanceof NoConnectionError) {
message = "Cannot connect to Internet...Please check your connection!";
} else if (error instanceof TimeoutError) {
message = "Connection TimeOut! Please check your internet connection.";
}
Log.e("VOLLEYERROR", message);
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
})
{
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("prm_1", nopol);
params.put("project", project);
if (flag_menu == 1) {
params.put("from", tvfrom.getText().toString());
params.put("to", tvto.getText().toString());
}
return params;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
String credentials = "admin_it" + ":" + "admin123";
String auth = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
headers.put("Authorization", auth);
return headers;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(60000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
MySingleton.getInstance(getApplicationContext()).addToRequestQueue(stringRequest);
}
public void getNopol(final String project) {
Log.d("PILIHNOPOL", "NOPOL");
//Get all police Number
StringRequest stringRequest = new StringRequest(Request.Method.POST, Config.GET_NOPOL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
nop.clear();
if (flag_menu == 0) {
nop.add("all");
}
try {
JSONObject json = new JSONObject(response);
JSONArray jsonArray = json.getJSONArray("nopol");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
String plat = obj.getString("vehicle_number").replace(" ", "");
nop.add(plat);
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(Maps.this, android.R.layout.simple_list_item_1, nop);
search.setAdapter(arrayAdapter);
search.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
pilih = parent.getItemAtPosition(position).toString();
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
mMap.clear();
startmark = null;
livelatlng.clear();
arstart.clear();
lastloc.clear();
if (flag_menu != 1) {
getcarloc(pilih, projectselect);
}
//Live Tracking selected
if (flag_menu == 2) {
if (live.getState().equals("TIMED_WAITING")) {
live.interrupt();
try {
live.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
live = new Thread() {
@Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000 * 76);
runOnUiThread(new Runnable() {
@Override
public void run() {
getcarloc(pilih, projectselect);
}
});
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
live.start();
}
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("NORESPONSE", String.valueOf(error));
}
}
) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("project", project);
return params;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
String credentials = "admin_it" + ":" + "admin123";
String auth = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
headers.put("Authorization", auth);
return headers;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(60000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
MySingleton.getInstance(getApplicationContext()).addToRequestQueue(stringRequest);
}
}
这是我的图书馆
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.3.0'
compile 'com.android.support:design:25.3.0'
compile 'com.android.support:cardview-v7:25.3.0'
compile 'com.google.android.gms:play-services-maps:10.2.1'
compile 'com.google.android.gms:play-services-location:10.2.1'
compile 'com.akexorcist:googledirectionlibrary:1.0.4'
compile 'cn.pedant.sweetalert:library:1.3'
compile 'com.android.volley:volley:1.0.0'
compile 'com.wdullaer:materialdatetimepicker:2.3.0'
compile 'com.android.support.constraint:constraint-layout:1.0.1'
testCompile 'junit:junit:4.12'
}
答案 0 :(得分:0)
您在onCreate()
方法中对谷歌地图的处理似乎与我使用和看到的略有不同。请尝试使用此代码:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this); // don't pass Maps.this
// rest of your code here
}
我的预感是,不知怎的,你两次绑定了监听器,但我无法在不尝试在本地复制你的实际代码的情况下证明这一点。