朋友们,我想在我的应用程序中显示我的自定义谷歌地图中的商家位置,所以我使用了我的地图,并且我用csv文件和我的地方上传了两个地方,并用于搜索地点,搜索谷歌的api看到我的下面的代码
MainActivity.java
public class MainActivity extends FragmentActivity implements TextWatcher {
final int RQS_GooglePlayServices = 1;
static GoogleMap myMap;
static double lat;
static double lng;
static String address;
static String title;
ArrayList<LatLng> markerPoints;
ProgressDialog mProgressDialog;
Context mContext;
SearchAddess mSearchAddess;
LinearLayout mLinearLayout_search_input;
ImageButton mButtonFind;
ImageButton mButtonSearch;
ImageButton mButtonDistance;
ImageButton mImageButtonDistanceFromTo;
ImageButton mImageButtonMultipleMarker;
LinearLayout mLinearLayoutFromTo;
EditText mEditTextFrom;
Button mButtonGo;
AddressLookup mAddressLookup;
RelativeLayout mRelativeLayout;
private LocationManager locationManager;
private String provider;
static Marker startPerc;
Marker marker;
EditText mAutoCompleteTextViewAddress;
String getsearchingAddress;
String[] mPlaceType=null;
String[] mPlaceTypeName=null;
String[] mKmName=null;
String [] mStringsDialogOption=null;
public double latitude;
public double longitude;
LatLng mLatLng;
public static double CurrentLatitude;
public static double CurrentLongitude;
GPSTracker gps;
Spinner mSpinner;
Spinner mSpinnerKm;
double mDoubleKm=0.0;
private GoogleApiClient mGoogleApiClient;
Button mButtonFindPlace;
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main );
mContext = this;
mIntent=new Intent();
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork() // or .detectAll() for all detectable problems
.penaltyLog()
.build());
markerPoints = new ArrayList<LatLng>();
mLinearLayout_search_input = (LinearLayout) findViewById(R.id.main_search_input_ll);
mSpinnerKm=(Spinner)findViewById(R.id.spr_km);
mButtonSearch = (ImageButton) findViewById(R.id.mButtonSearch);
mButtonFind = (ImageButton) findViewById(R.id.mbtn_cancel);
mButtonFindPlace=(Button)findViewById(R.id.btn_find_palce);
mSpinner=(Spinner)findViewById(R.id.spr_place_type);
mButtonDistance=(ImageButton)findViewById(R.id.mButtonDistance);
mImageButtonDistanceFromTo=(ImageButton)findViewById(R.id.mButtonDistanceFromTo);
mImageButtonMultipleMarker=(ImageButton)findViewById(R.id.mButtonMultipleMarker);
mEditTextFrom=(EditText)findViewById(R.id.editTextFrom);
mButtonGo=(Button)findViewById(R.id.buttonGo);
mRelativeLayout=(RelativeLayout)findViewById(R.id.main_search_input_rl);
mAutoCompleteTextViewAddress = (EditText) findViewById(R.id.autocompleteview_address);
gps = new GPSTracker(MainActivity.this);
// check if GPS enabled
if(gps.canGetLocation()){
CurrentLatitude = gps.getLatitude();
CurrentLongitude = gps.getLongitude();
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
// Array of place types
mPlaceType = getResources().getStringArray(R.array.place_type);
// Array of place type names
mPlaceTypeName = getResources().getStringArray(R.array.place_type_name);
mKmName = getResources().getStringArray(R.array.km_name);
mStringsDialogOption = getResources().getStringArray(R.array.dialog_option);
// Creating an array adapter with an array of Place types
// to populate the spinner
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, mPlaceTypeName);
mSpinner.setAdapter(adapter);
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, mKmName);
mSpinnerKm.setAdapter(adapter1);
// Setting click event lister for the find button
mButtonFindPlace.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
int selectedPosition = mSpinner.getSelectedItemPosition();
String type = mPlaceType[selectedPosition];
String type1 = mKmName[mSpinnerKm.getSelectedItemPosition()];
String ss[]=type1.split(" ");
String s=ss[0];
mDoubleKm=1000 * Double.valueOf(s);
StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
sb.append("location="+CurrentLatitude+","+CurrentLongitude);
sb.append("&radius="+String.valueOf(mDoubleKm));
sb.append("&types="+type);
sb.append("&sensor=true");
sb.append("&key=AIzaSyDst4th70R2y2kaExv10UIr7cxS3KQUejs");
// Creating a new non-ui thread task to download Google place json data
PlacesTask placesTask = new PlacesTask();
// Invokes the "doInBackground()" method of the class PlaceTask
placesTask.execute(sb.toString());
}
});
initMap();
}
/** A class, to download Google Places */
private class PlacesTask extends AsyncTask<String, Integer, String>{
String data = null;
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
mProgressDialog = ProgressDialog.show(MainActivity.this,getString(R.string.wait) ,getString(R.string.searching_place));
}
// Invoked by execute() method of this object
@Override
protected String doInBackground(String... url) {
try{
data = downloadUrlNearByPlace(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
// Executed after the complete execution of doInBackground() method
@Override
protected void onPostExecute(String result){
ParserNearByTask parserTask = new ParserNearByTask();
// Start parsing the Google places in JSON format
// Invokes the "doInBackground()" method of the class ParseTask
parserTask.execute(result);
}
}
/** A method to download json data from url */
private String downloadUrlNearByPlace(String strUrl) throws IOException{
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try{
URL url = new URL(strUrl);
System.out.println("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;
}
/** A class to parse the Google Places in JSON format */
private class ParserNearByTask extends AsyncTask<String, Integer, List<HashMap<String,String>>>{
JSONObject jObject;
// Invoked by execute() method of this object
@Override
protected List<HashMap<String,String>> doInBackground(String... jsonData) {
List<HashMap<String, String>> places = null;
PlaceJSONParser placeJsonParser = new PlaceJSONParser();
try{
jObject = new JSONObject(jsonData[0]);
/** Getting the parsed data as a List construct */
places = placeJsonParser.parse(jObject);
}catch(Exception e){
Log.d("Exception",e.toString());
}
return places;
}
// Executed after the complete execution of doInBackground() method
@Override
protected void onPostExecute(List<HashMap<String,String>> list){
if(mProgressDialog!=null)
{
mProgressDialog.dismiss();
}
// Clears all the existing markers
myMap.clear();
for(int i=0;i<list.size();i++){
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
// Getting a place from the places list
HashMap<String, String> hmPlace = list.get(i);
System.out.println("Get name "+ hmPlace.get("place_name"));
// Getting latitude of the place
double lat = Double.parseDouble(hmPlace.get("lat"));
// Getting longitude of the place
double lng = Double.parseDouble(hmPlace.get("lng"));
// Getting name
String name = hmPlace.get("place_name");
// Getting vicinity
String vicinity = hmPlace.get("vicinity");
LatLng latLng = new LatLng(lat, lng);
// Setting the position for the marker
markerOptions.position(latLng);
// Setting the title for the marker.
//This will be displayed on taping the marker
markerOptions.title(name + " : " + vicinity);
// Placing a marker on the touched position
myMap.addMarker(markerOptions);
myMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(CurrentLatitude, CurrentLongitude), 12));
}
}
}
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.cd:
gps = new GPSTracker(MainActivity.this);
// check if GPS enabled
if(gps.canGetLocation()){
CurrentLatitude = gps.getLatitude();
CurrentLongitude = gps.getLongitude();
// \n is for new line
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
initMap();
case R.id.normal:
myMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
return true;
case R.id.satelite:
myMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
return true;
case R.id.hybride:
myMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
return true;
case R.id.tarrin:
myMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void hideKeyBoard()
{
InputMethodManager imm = (InputMethodManager)getSystemService(
Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mAutoCompleteTextViewAddress.getWindowToken(), 0);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void initMap()
{
FragmentManager myFragmentManager = getSupportFragmentManager();
SupportMapFragment mySupportMapFragment = (SupportMapFragment) myFragmentManager
.findFragmentById(R.id.map);
myMap = mySupportMapFragment.getMap();
if (myMap != null)
{
myMap.setMyLocationEnabled(true);
myMap.getUiSettings().setZoomControlsEnabled(true);
myMap.getUiSettings().setCompassEnabled(true);
myMap.getUiSettings().setMyLocationButtonEnabled(true);
myMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
else
{
System.out.println("Null Value");
}
if(myMap!=null)
{
// Enable MyLocation Button in the Map
myMap.setMyLocationEnabled(true);
getAddressFromLatLong(CurrentLatitude, CurrentLongitude);
// Setting onclick event listener for the map
}
mButtonFind.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
mButtonSearch.setVisibility(View.VISIBLE);
mLinearLayout_search_input.setVisibility(View.GONE);
getLatLongFromAddress(mAutoCompleteTextViewAddress.getText().toString().trim());
hideKeyBoard();
}
});
}
// Fetches data from url passed
private class DownloadTask extends AsyncTask<String, Void, String>{
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
mProgressDialog = ProgressDialog.show(MainActivity.this,getString(R.string.wait) ,getString(R.string.route_draw));
}
// Downloading data in non-ui thread
@Override
protected String doInBackground(String... url) {
// For storing data from web service
String data = "";
try{
// Fetching the data from web service
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
// Executes in UI thread, after the execution of
// doInBackground()
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ParserTask parserTask = new ParserTask();
// Invokes the thread for parsing the JSON data
parserTask.execute(result);
}
}
/** A class to parse the Google Places in JSON format */
private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String,String>>> >{
// Parsing the data in non-ui thread
@Override
protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try{
jObject = new JSONObject(jsonData[0]);
DirectionsJSONParser parser = new DirectionsJSONParser();
// Starts parsing data
routes = parser.parse(jObject);
}catch(Exception e){
e.printStackTrace();
}
return routes;
}
// Executes in UI thread, after the parsing process
@Override
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
if(mProgressDialog!=null)
{
mProgressDialog.dismiss();
}
if (myMap!=null)
{
ArrayList<LatLng> points = null;
PolylineOptions lineOptions = null;
MarkerOptions markerOptions = new MarkerOptions();
// Traversing through all the routes
for(int i=0;i<result.size();i++){
points = new ArrayList<LatLng>();
lineOptions = new PolylineOptions();
// Fetching i-th route
List<HashMap<String, String>> path = result.get(i);
// Fetching all the points in i-th route
for(int j=0;j<path.size();j++){
HashMap<String,String> point = path.get(j);
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
// Adding all the points in the route to LineOptions
lineOptions.addAll(points);
lineOptions.width(2);
lineOptions.color(Color.RED);
}
// Drawing polyline in the Google Map for the i-th route
myMap.addPolyline(lineOptions);
}
}
}
/** 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;
}
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;
}
@Override
public void afterTextChanged(Editable s) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
getLatLongFromAddress(mAutoCompleteTextViewAddress.getText().toString().trim());
}
public static void getLatLongFromAddress(String youraddress)
{
HttpGet httpGet = new HttpGet("http://maps.google.com/maps/api/geocode/json?address=" +youraddress+"&sensor=false");
HttpClient client = new DefaultHttpClient();
HttpResponse response;
StringBuilder stringBuilder = new StringBuilder();
try {
response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
JSONObject jsonObject = new JSONObject();
try {
jsonObject = new JSONObject(stringBuilder.toString());
lng = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
.getJSONObject("geometry").getJSONObject("location")
.getDouble("lng");
lat = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
.getJSONObject("geometry").getJSONObject("location")
.getDouble("lat");
address=((JSONArray)jsonObject.get("results")).getJSONObject(0).getString("formatted_address");
System.out.println("Lat "+lat);
System.out.println("Lng "+lng);
System.out.println("address"+address);
startPerc = myMap.addMarker(new MarkerOptions()
.position(new LatLng(lat, lng))
.title(address));
myMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 12.0f));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getAddressFromLatLong(double currentLatitude,
double currentLongitude)
{
HttpGet httpGet = new HttpGet("http://maps.googleapis.com/maps/api/geocode/json?latlng=" +currentLatitude+","+currentLongitude+"&sensor=false");
HttpClient client = new DefaultHttpClient();
HttpResponse response;
StringBuilder stringBuilder = new StringBuilder();
try {
response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
JSONObject jsonObject = new JSONObject();
try
{
jsonObject = new JSONObject(stringBuilder.toString());
lng = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
.getJSONObject("geometry").getJSONObject("location")
.getDouble("lng");
lat = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
.getJSONObject("geometry").getJSONObject("location")
.getDouble("lat");
address=((JSONArray)jsonObject.get("results")).getJSONObject(0).getString("formatted_address");
startPerc = myMap.addMarker(new MarkerOptions()
.position(new LatLng(lat, lng))
.title(address).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW)));
myMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 12.0f));
System.out.println("Lat "+lat);
System.out.println("Lng "+lng);
System.out.println("address "+address);
} catch (JSONException e) {
e.printStackTrace();
}
return address;
}
@Override
protected void onResume()
{
super.onResume();
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getApplicationContext());
if (resultCode == ConnectionResult.SUCCESS)
{
// Toast.makeText(getApplicationContext(),
// "isGooglePlayServicesAvailable SUCCESS", Toast.LENGTH_LONG)
// .show();
}
else
{
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
RQS_GooglePlayServices);
}
}
@Override
protected void onPause() {
super.onPause();
}
}
当我运行上面的代码时,它没有显示我的业务地点,我添加了我的csv文件,所以任何想法如何在我的应用程序中显示?