如何能够显示标记的地名而不是从 mysql 数据库检索的经度、纬度?
How to be able to show marker's place name instead of longitude,latitude that retrieve from mysql database?
我一直在关注此站点的教程:“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 文件,以便能够从我的远程 mysql 数据库读取 'place_name':
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);
}
?>
不要评论这一行。
markerOptions.title(name);
这将在您的标记上设置标题。
在 MarkerJSONParser class 中,您必须添加:
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;
}
在 PostExecute 的 MainActivity 中添加:
String place_name=marker.get("place_name");
我一直在关注此站点的教程:“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 文件,以便能够从我的远程 mysql 数据库读取 'place_name':
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);
}
?>
不要评论这一行。
markerOptions.title(name);
这将在您的标记上设置标题。
在 MarkerJSONParser class 中,您必须添加:
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;
}
在 PostExecute 的 MainActivity 中添加:
String place_name=marker.get("place_name");