package com.usai.apex; //import com.google.android.gms.maps.SupportMapFragment; //import baidumapsdk.demo.DemoApplication; //import baidumapsdk.demo.DemoApplication.MyGeneralListener; import java.util.ArrayList; import java.util.HashMap; import org.json.JSONException; import org.json.JSONObject; //import baidumapsdk.demo.R; import com.baidu.location.BDLocation; import com.baidu.location.BDLocationListener; import com.baidu.location.LocationClient; import com.baidu.location.LocationClientOption; import com.baidu.mapapi.BMapManager; import com.baidu.mapapi.SDKInitializer; import com.baidu.mapapi.map.BaiduMap.OnMapClickListener; import com.baidu.mapapi.map.BitmapDescriptor; import com.baidu.mapapi.map.BitmapDescriptorFactory; import com.baidu.mapapi.map.InfoWindow; import com.baidu.mapapi.map.MapPoi; import com.baidu.mapapi.map.MapStatusUpdate; import com.baidu.mapapi.map.MapStatusUpdateFactory; //import com.baidu.mapapi.MKGeneralListener; //import com.baidu.mapapi.map.ItemizedOverlay; //import com.baidu.mapapi.map.MKEvent; //import com.baidu.mapapi.map.MapController; import com.baidu.mapapi.map.MapView; import com.baidu.mapapi.map.Marker; import com.baidu.mapapi.map.MarkerOptions; //import com.baidu.mapapi.map.OverlayItem; //import com.baidu.mapapi.map.PopupClickListener; //import com.baidu.mapapi.map.PopupOverlay; import com.baidu.mapapi.map.MyLocationData; import com.baidu.mapapi.map.SupportMapFragment; import com.baidu.mapapi.map.BaiduMap.OnMarkerClickListener; import com.baidu.mapapi.map.InfoWindow.OnInfoWindowClickListener; import com.baidu.mapapi.model.LatLng; //import com.baidu.platform.comapi.basestruct.GeoPoint; import com.usai.util.Network; import android.Manifest; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.location.LocationListener; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.ActivityCompat; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class BaiduMapFragment extends Fragment implements BDLocationListener { private SearchTask m_task = null; String fragment_content = null; private MapView mMapView = null; // private MyOverlay mOverlay = null; // private OverlayItem mCurItem = null; // private Button button = null; // private ArrayList mItems = null; // private PopupOverlay pop = null; SupportMapFragment fragment; BMapManager mBMapManager = null; public static boolean m_bKeyRight = true; HashMap marker_detail = new HashMap(); // OverlayItem m_curitem = null; /* * public class MyOverlay extends ItemizedOverlay { * * public MyOverlay(Drawable defaultMarker, MapView mapView) { * super(defaultMarker, mapView); } * * @Override public boolean onTap(int index) { * Log.d("baidumap...................", "ontap"); View viewCache = * getActivity().getLayoutInflater().inflate( R.layout.marker_view, null); * * TextView tv_title = (TextView) viewCache .findViewById(R.id.tv_title); * TextView tv_info = (TextView) viewCache.findViewById(R.id.tv_info); * * OverlayItem item = getItem(index); * * tv_title.setText(item.getTitle()); tv_info.setText(item.getSnippet()); * m_curitem = item; pop.showPopup(viewCache, item.getPoint(), 32); return * true; } * * @Override public boolean onTap(GeoPoint pt, MapView mMapView) { * Log.d("baidu map demo ", "hide pop"); if (pop != null) { * * pop.hidePop(); // mMapView.removeView(button); } return false; } * * } */ void AddMarker() { if (mMapView == null) { Log.d("onResume", "get map from fragment"); mMapView = fragment.getMapView(); if (mMapView == null) return; } try { JSONObject jsobj = new JSONObject(fragment_content); int count = jsobj.getInt("total"); JSONObject objrecords = jsobj.getJSONObject("records"); // mOverlay = new MyOverlay(getResources().getDrawable( // R.drawable.ic_marker), mMapView); BitmapDescriptor icon = BitmapDescriptorFactory .fromResource(R.drawable.ic_marker); for (int i = 0; i < count; i++) { // offset++; JSONObject objrec = objrecords.getJSONObject("record" + i); String area = objrec.getString("area"); String company = objrec.getString("company"); String city = objrec.getString("city"); String longitude = objrec.getString("longitude"); String latitude = objrec.getString("latitude"); String address = objrec.getString("address"); String telephone = objrec.getString("telephone"); String fax = objrec.getString("fax"); String contact = objrec.getString("contact"); String email = objrec.getString("email"); LocationDetail detail = new LocationDetail(company, address, telephone, fax, contact, email); marker_detail.put(company, detail); Bundle extrainfo = new Bundle(); extrainfo.putString("company", company); extrainfo.putSerializable("detail", detail); extrainfo.putSerializable("city", city); extrainfo.putSerializable("area", area); // // 准备overlay 数据 // // GeoPoint p1 = new GeoPoint( // (int) (Double.parseDouble(latitude) * 1E6), // (int) (Double.parseDouble(longitude) * 1E6)); // OverlayItem item1 = new OverlayItem(p1, company, city + "\n" // + area); // // // // // * 将item 添加到overlay中 注意: 同一个itme只能add一次 // // // mOverlay.addItem(item1); LatLng llA = new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude)); MarkerOptions markeroption = new MarkerOptions().position(llA) .icon(icon).zIndex(9).title(company) .extraInfo(extrainfo).draggable(true); // if (animationBox.isChecked()) { // //掉下动画 // ooA.animateType(MarkerAnimateType.drop); // } Marker mMarkerA = (Marker) (mMapView.getMap() .addOverlay(markeroption)); } // // * 保存所有item,以便overlay在reset后重新添加 // // mItems = new ArrayList(); // mItems.addAll(mOverlay.getAllItem()); // // // // * 将overlay 添加至MapView中 // // // mMapView.getOverlays().add(mOverlay); // // // // * 刷新地图 // // // mMapView.refresh(); // PopupClickListener popListener = new PopupClickListener() // { // @Override // public void onClickedPopup(int index) // { // Log.d("baidu map.......", "popup on click"); // pop.hidePop(); // // mMapView.refresh(); // Intent intent = new Intent(); // intent.setClass(getActivity(), LocationDetailActivity.class); // // String markertext = m_curitem.getTitle(); // // intent.putExtra("detail", marker_detail.get(markertext)); // // // intent.putExtra("password", password); // // intent.putExtra("function_name", function_name); // // intent.putExtra("behavior", Network.BEHAVIOR_SEARCH); // startActivity(intent); // // } // }; // pop = new PopupOverlay(mMapView, popListener); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void requestloactions() { if (m_task != null) { return; } if (fragment_content != null) { // LayoutInflater inflater = (LayoutInflater) // ApexTrackingApplication // .get_instance().getSystemService( // Context.LAYOUT_INFLATER_SERVICE); // init(fragment_content,inflater); return; } // mStatusMessageView.setText(R.string.str_Loading); // showProgress(true); m_task = new SearchTask(); // TextView text_page = (TextView) view_page_footer // .findViewById(R.id.text_page); // text_page.setText("Loading..."); // text_page.setEnabled(false); m_task.execute(); } private LocationClient mLocationClient; private void initLocation() { //定位客户端的设置 mLocationClient = new LocationClient(getContext()); //注册监听 mLocationClient.registerLocationListener(this); //配置定位 LocationClientOption option = new LocationClientOption(); option.setCoorType("bd09ll");//坐标类型 option.setIsNeedAddress(true);//可选,设置是否需要地址信息,默认不需要 option.setOpenGps(true);//打开Gps option.setScanSpan(1000);//1000毫秒定位一次 option.setIsNeedLocationPoiList(true);//可选,默认false,设置是否需要POI结果,可以在BDLocation.getPoiList里得到 mLocationClient.setLocOption(option); } @Override public void onReceiveLocation(BDLocation bdLocation) { //将获取的location信息给百度map MyLocationData data = new MyLocationData.Builder() .accuracy(bdLocation.getRadius()) // 此处设置开发者获取到的方向信息,顺时针0-360 .direction(100) .latitude(bdLocation.getLatitude()) .longitude(bdLocation.getLongitude()) .build(); if (fragment != null) { fragment.getMapView().getMap().setMyLocationData(data); } } class SearchTask extends AsyncTask { int errorcode; // boolean bfinish = false; @Override protected Boolean doInBackground(Void... params) { Log.d("SearchTask", "doInBackground"); if (!Network.NetworkIsAvailable()) { errorcode = Network.RESULT_NET_NOTAVAILABLE; return false; } String jstr = Network.get_servicelocation(); if (jstr == null || jstr.length() <= 0) { // Log.d(TAG, "json is wrong"); errorcode = Network.RESULT_NET_ERROR; return false; } JSONObject jsobj; // // array = new JSONArray(json); try { jsobj = new JSONObject(jstr); // if (searchresult.get_fieldscount() == 0) // { // JSONObject objfields = jsobj.getJSONObject("fields"); // if (objfields != null) // searchresult.init_fields(objfields.toString()); // } int count = jsobj.getInt("total"); // if (count < limit) // bfinish = true; JSONObject objrecords = jsobj.getJSONObject("records"); if (objrecords != null) { fragment_content = jstr; errorcode = Network.RESULT_TRUE; return true; } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } errorcode = Network.RESULT_NET_ERROR; return false; } @Override protected void onPostExecute(Boolean success) { String tag = "onPostExecute@BaiduMapFragment"; Log.d(tag, "entry"); m_task = null; // showProgress(false); switch (errorcode) { case Network.RESULT_NET_NOTAVAILABLE: { Toast toast = Toast.makeText( ApexTrackingApplication.get_instance(), getText(R.string.msg_connection_none), Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); break; } case Network.RESULT_NET_ERROR: { Toast toast = Toast.makeText( ApexTrackingApplication.get_instance(), getText(R.string.msg_net_error), Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); break; } case Network.RESULT_ERROR: // case Network.RESULT_RESPONSE_NULL: { Toast toast = Toast.makeText( ApexTrackingApplication.get_instance(), getText(R.string.msg_net_resulterror), Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); break; } default: break; } if (success) { AddMarker(); mMapView.getMap().setOnMapClickListener( new OnMapClickListener() { @Override public boolean onMapPoiClick(MapPoi arg0) { mMapView.getMap().hideInfoWindow(); return false; } @Override public void onMapClick(LatLng arg0) { mMapView.getMap().hideInfoWindow(); } }); mMapView.getMap().setOnMarkerClickListener( new OnMarkerClickListener() { public boolean onMarkerClick(final Marker marker) { // Button button = new // Button(getActivity().getApplicationContext()); // button.setBackgroundResource(R.drawable.popup); View viewCache = getActivity() .getLayoutInflater().inflate( R.layout.marker_view, null); TextView tv_title = (TextView) viewCache .findViewById(R.id.tv_title); TextView tv_info = (TextView) viewCache .findViewById(R.id.tv_info); final String title = marker.getTitle(); Bundle bundle = marker.getExtraInfo(); final LocationDetail detail = (LocationDetail) bundle .getSerializable("detail"); String city = bundle.getString("city"); String area = bundle.getString("area"); // OverlayItem item = getItem(index); // marker.get tv_title.setText(title); tv_info.setText(city + "\n" + area); // m_curitem = item; // pop.showPopup(viewCache, item.getPoint(), // 32); OnInfoWindowClickListener listener = null; if (true) { // button.setText("更改位置"); listener = new OnInfoWindowClickListener() { public void onInfoWindowClick() { mMapView.getMap().hideInfoWindow(); Log.d("baidu map.......", "popup on click"); // mMapView.refresh(); Intent intent = new Intent(); intent.setClass( getActivity(), LocationDetailActivity.class); String markertext = title; intent.putExtra("detail", detail); // // intent.putExtra("password", // password); // intent.putExtra("function_name", // function_name); // intent.putExtra("behavior", // Network.BEHAVIOR_SEARCH); // startActivity(intent); LocationDetail detail = marker_detail.get(markertext); if (markerClickListener != null) { markerClickListener.markerClicked(detail); } } }; LatLng ll = marker.getPosition(); InfoWindow mInfoWindow = new InfoWindow( BitmapDescriptorFactory .fromView(viewCache), ll, -100, listener); mMapView.getMap().showInfoWindow( mInfoWindow); } // else if (marker == mMarkerB) { // button.setText("更改图标"); // button.setOnClickListener(new // OnClickListener() { // public void onClick(View v) { // marker.setIcon(bd); // mBaiduMap.hideInfoWindow(); // } // }); // LatLng ll = marker.getPosition(); // mInfoWindow = new InfoWindow(button, ll, // -47); // mBaiduMap.showInfoWindow(mInfoWindow); // } else if (marker == mMarkerC) { // button.setText("删除"); // button.setOnClickListener(new // OnClickListener() { // public void onClick(View v) { // marker.remove(); // mBaiduMap.hideInfoWindow(); // } // }); // LatLng ll = marker.getPosition(); // mInfoWindow = new InfoWindow(button, ll, // -47); // mBaiduMap.showInfoWindow(mInfoWindow); // } return true; } }); // // if (bfinish) // { // // getListView().removeFooterView(view_page_footer); // // Toast.makeText(AnnouncementActivity.this, "Load all!", // // Toast.LENGTH_LONG).show(); // // TextView tv = (TextView) view_page_footer // .findViewById(R.id.text_page); // tv.setText("No more items"); // tv.setEnabled(false); // } // else // { // TextView tv = (TextView) view_page_footer // .findViewById(R.id.text_page); // tv.setText("More..."); // tv.setEnabled(true); // } // adapter.notifyDataSetChanged(); // // getListAdapter().notifyDataSetChanged; // // BaseAdapter mJson = null; // // mJson.notifyDataSetChanged(); } super.onPostExecute(success); } @Override protected void onCancelled() { m_task = null; // showProgress(false); } } public void initEngineManager(Context context) { SDKInitializer.initialize(ApexTrackingApplication.get_instance()); // String strKey = ApexTrackingApplication.get_instance().getString( // R.string.baidu_key); // if (mBMapManager == null) // { // mBMapManager = new BMapManager(context); // } // // if (!mBMapManager.init(strKey, new MyGeneralListener())) // { // // Toast.makeText(getActivity().getApplicationContext(), // // "BMapManager 初始化错误!", Toast.LENGTH_LONG).show(); // } } /* * // 常用事件监听,用来处理通常的网络错误,授权验证错误等 static class MyGeneralListener implements * MKGeneralListener { * * @Override public void onGetNetworkState(int iError) { if (iError == * MKEvent.ERROR_NETWORK_CONNECT) { // Toast.makeText( // * ApexTrackingApplication.get_instance() // .getApplicationContext(), * "您的网络出错啦!", // Toast.LENGTH_LONG).show(); } else if (iError == * MKEvent.ERROR_NETWORK_DATA) { // Toast.makeText( // * ApexTrackingApplication.get_instance() // .getApplicationContext(), * "输入正确的检索条件!", // Toast.LENGTH_LONG).show(); } // ... } * * @Override public void onGetPermissionState(int iError) { // 非零值表示key验证未通过 * if (iError != 0) { // 授权Key错误: // Toast.makeText( // * ApexTrackingApplication.get_instance() // .getApplicationContext(), // * "请在 DemoApplication.java文件输入正确的授权Key,并检查您的网络连接是否正常!error: " // + iError, * Toast.LENGTH_LONG).show(); m_bKeyRight = false; } else { m_bKeyRight = * true; // Toast.makeText( // ApexTrackingApplication.get_instance() // * .getApplicationContext(), "key认证成功", // Toast.LENGTH_LONG).show(); } } } */ @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); initEngineManager(getActivity().getApplicationContext()); FragmentManager fm = getChildFragmentManager(); fragment = (SupportMapFragment) fm.findFragmentById(R.id.map); if (fragment == null) { Log.d("onActivityCreated", "create support map fragment"); fragment = SupportMapFragment.newInstance(); ;// .newInstance(); fm.beginTransaction().replace(R.id.map, fragment).commit(); } mMapView = fragment.getMapView(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub // return super.onCreateView(inflater, container, savedInstanceState); requestloactions(); return inflater.inflate(R.layout.fragment_service_location, container, false); } @Override public void onResume() { super.onResume(); Log.d("onResume", "get map from fragment"); LatLng center = new LatLng(29.945,104.7); MapStatusUpdate msu = MapStatusUpdateFactory.newLatLngZoom(center,4.8f);//MapStatusUpdateFactory.zoomTo(4.5f); fragment.getMapView().getMap().setMapStatus(msu); // float zoomLevel = Float.parseFloat(t.getText().toString()); // MapStatusUpdate u = MapStatusUpdateFactory.zoomTo(zoomLevel); // mBaiduMap.animateMapStatus(u); // MapController controller = fragment.getMapView().getController(); // controller.setCenter(new GeoPoint((int) ( * 1E6), // (int) * 1E6))); // controller.setZoom(5); if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. } else { fragment.getMapView().getMap().setMyLocationEnabled(true); initLocation(); if(mLocationClient != null && !mLocationClient.isStarted()){//如果定位client没有开启,开启定位 mLocationClient.start(); } } } @Override public void onPause() { super.onPause(); if(mLocationClient != null && mLocationClient.isStarted()){//如果定位client开启,关闭定位 mLocationClient.stop(); } } public BaiduMarkerClickListener markerClickListener; public interface BaiduMarkerClickListener { void markerClicked(LocationDetail detail); } }