Я следую учебному пособию с этого сайта: ‘http://wptrafficanalyzer.in/blog/storing-google-maps-android-api-v2-marker-locations-in-mysql/и застрял с этими кодами на несколько дней. Моя проблема в том, что я не могу показать название маркера с названием места вместо долготы и широты, как сказано в учебнике. Я уже добавляю имя строки, но когда я пытаюсь запустить приложение, маркер не показывает заголовок. Пожалуйста, помогите мне….
MainActivity.java
public class MainActivity extends FragmentActivity implements LocationListener {
GoogleMap mGoogleMap;
double mLatitude=0;
double mLongitude=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
if(status!= ConnectionResult.SUCCESS){ // Google Play Services are not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();
}else { // Google Play Services are available
// Getting reference to SupportMapFragment
SupportMapFragment fragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
// Creating GoogleMap from SupportMapFragment
mGoogleMap = fragment.getMap();
// Enabling MyLocation button for the Google Map
mGoogleMap.setMyLocationEnabled(true);
// 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();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location From GPS
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
// Setting OnClickEvent listener for the GoogleMap
/* mGoogleMap.setOnMapClickListener(new OnMapClickListener() {
@Override
public void onMapClick(LatLng latlng) {
addMarker(latlng);
sendToServer(latlng);
}
}); */
// Starting locations retrieve task
new RetrieveTask().execute();
}
}
// Adding marker on the GoogleMaps
private void addMarker(LatLng latlng) {
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latlng);
markerOptions.title(name);
String name ="place_name";
//markerOptions.title(latlng.latitude + "," + latlng.longitude);
markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.restoicon));
mGoogleMap.addMarker(markerOptions);
}
// Invoking background thread to store the touched location in Remove MySQL server
/*private void sendToServer(LatLng latlng) {
new SaveTask().execute(latlng);
}
// Background thread to save the location in remove MySQL server
private class SaveTask extends AsyncTask<LatLng, Void, Void> {
@Override
protected Void doInBackground(LatLng... params) {
String lat = Double.toString(params[0].latitude);
String lng = Double.toString(params[0].longitude);
String strUrl = "http://my-url/save.php"; //http://192.168.0.105/location_marker_mysql/save.php
URL url = null;
try {
url = new URL(strUrl);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
connection.getOutputStream());
outputStreamWriter.write("lat=" + lat + "&lng="+lng);
outputStreamWriter.flush();
outputStreamWriter.close();
InputStream iStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new
InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( (line = reader.readLine()) != null){
sb.append(line);
}
reader.close();
iStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
} */
// Background task to retrieve locations from remote mysql server
private class RetrieveTask extends AsyncTask<Void, Void, String>{
@Override
protected String doInBackground(Void... params) {
String strUrl = "http://my-url/retrieve.php"; //http://192.168.0.105/location_marker_mysql/retrieve.php
URL url = null;
StringBuffer sb = new StringBuffer();
try {
url = new URL(strUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream iStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(iStream));
String line = "";
while( (line = reader.readLine()) != null){
sb.append(line);
}
reader.close();
iStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
new ParserTask().execute(result);
}
}
// Background thread to parse the JSON data retrieved from MySQL server
private class ParserTask extends AsyncTask<String, Void, List<HashMap<String, String>>>{
@Override
protected List<HashMap<String,String>> doInBackground(String... params) {
MarkerJSONParser markerParser = new MarkerJSONParser();
JSONObject json = null;
try {
json = new JSONObject(params[0]);
} catch (JSONException e) {
e.printStackTrace();
}
List<HashMap<String, String>> markersList = markerParser.parse(json);
return markersList;
}
@Override
protected void onPostExecute(List<HashMap<String, String>> result) {
for(int i=0; i<result.size();i++){
//Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
HashMap<String, String> marker = result.get(i);
//LatLng latlng = new LatLng(Double.parseDouble(marker.get("lat")), Double.parseDouble(marker.get("lng")));
// Getting latitude of the place
double lat = Double.parseDouble(marker.get("lat"));
// Getting longitude of the place
double lng = Double.parseDouble(marker.get("lng"));
LatLng latlng= new LatLng(lat, lng);
markerOptions.position(latlng);
//addMarker(latlng);
//Setting the position for the marker
// Setting the title for the marker.
//This will be displayed on taping the marker
//use custom marker icon
markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.restoicon));
mGoogleMap.addMarker(markerOptions);
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public void onLocationChanged(Location location) {
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
LatLng latLng = new LatLng(mLatitude, mLongitude);
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(12));
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
MarkerJSONParser.java
public class MarkerJSONParser {
/** Receives a JSONObject and returns a list */
public List<HashMap<String,String>> parse(JSONObject jObject){
JSONArray jMarkers = null;
try {
/** Retrieves all the elements in the 'markers' array */
jMarkers = jObject.getJSONArray("markers");
} catch (JSONException e) {
e.printStackTrace();
}
/** Invoking getMarkers with the array of json object
* where each json object represent a marker
*/
return getMarkers(jMarkers);
}
private List<HashMap<String, String>> getMarkers(JSONArray jMarkers){
int markersCount = jMarkers.length();
List<HashMap<String, String>> markersList = new ArrayList<HashMap<String,String>>();
HashMap<String, String> marker = null;
/** Taking each marker, parses and adds to list object */
for(int i=0; i<markersCount;i++){
try {
/** Call getMarker with marker JSON object to parse the marker */
marker = getMarker((JSONObject)jMarkers.get(i));
markersList.add(marker);
}catch (JSONException e){
e.printStackTrace();
}
}
return markersList;
}
/** Parsing the Marker JSON object */
private HashMap<String, String> getMarker(JSONObject jMarker){
HashMap<String, String> marker = new HashMap<String, String>();
String lat = "-NA-";
String lng ="-NA-";
try {
// Extracting latitude, if available
if(!jMarker.isNull("lat")){
lat = jMarker.getString("lat");
}
// Extracting longitude, if available
if(!jMarker.isNull("lng")){
lng = jMarker.getString("lng");
}
marker.put("lat", lat);
marker.put("lng", lng);
} catch (JSONException e) {
e.printStackTrace();
}
return marker;
}
}
Я также редактирую этот php-файл, чтобы иметь возможность читать ‘place_name’ из моей удаленной базы данных mysql:
retrieve.php
<?php
require_once("config.php");
$markers = array();
$sql = "select place_name,lat,lng from markers";
$mysqli = new mysqli($host, $username, $password, $db_name);
if($res = $mysqli->query($sql)){
while($row=$res->fetch_assoc()){
$place_name = $row['place_name'];
$lat = $row['lat'];
$lng = $row['lng'];
$data= array("place_name"=>$place_name,"lat"=>$lat,"lng"=>$lng);
$marker[] = $data;
}
$markers = array("markers"=>$marker);
echo json_encode($markers);
}
?>
В классе MarkerJSONParser вы должны добавить:
private HashMap<String, String> getMarker(JSONObject jMarker){
HashMap<String, String> marker = new HashMap<String, String>();
String lat = "-NA-";
String lng ="-NA-";
String place_name ="-NA-";
try {
// Extracting latitude, if available
if(!jMarker.isNull("lat")){
lat = jMarker.getString("lat");
}
// Extracting longitude, if available
if(!jMarker.isNull("lng")){
lng = jMarker.getString("lng");
}
if(!jMarker.isNull("place_name"){
place_name = jMarker.getString("place_name");
}
marker.put("lat", lat);
marker.put("lng", lng);
marker.put("place_name",place_name);
} catch (JSONException e) {
e.printStackTrace();
}
return marker;
}
В MainActivity в PostExecute добавьте:
String place_name=marker.get("place_name");
Не комментируйте эту строку.
markerOptions.title(name);
Это установит заголовок на ваших маркерах.