问题描述
我想从我的MySQL数据库中创建的谷歌地图V2标记,它不工作。该地图不来了,但没有任何标记。任何一个可以告诉我什么是错的,什么我需要改变吗?我也试着具有getDouble是getDouble(0)和getDouble(1),但我读的地方,试图0和2。它也有一堆从多个教程,我已经试过进口。我将在稍后删除。
I'm trying to create markers on Google Maps v2 from my mySQL database and it is not working. The map does come up but there are no markers. Can any one tell me what is wrong and what I need to change? I've also tried having the getDouble be getDouble(0) and getDouble(1) but I read somewhere to try 0 and 2. It also has a bunch of imports from multiple tutorials I've tried. I'll remove later.
我的活动
进口com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Dialog;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.widget.TextView;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class ReadComments extends FragmentActivity {
private static final String LOG_TAG = "JsOn ErRoR";
private static final String SERVICE_URL = "my url";
protected GoogleMap mapB;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.get_local);
setUpMapIfNeeded();
}
@Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (mapB == null) {
mapB = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapB))
.getMap();
if (mapB != null) {
setUpMap();
}
}
}
private void setUpMap() {
new Thread(new Runnable() {
public void run() {
try {
retrieveAndAddCities();
} catch (IOException e) {
Log.e(LOG_TAG, "Cannot retrive cities", e);
return;
}
}
}).start();
}
protected void retrieveAndAddCities() throws IOException {
HttpURLConnection conn = null;
final StringBuilder json = new StringBuilder();
try {
// Connect to the web service
URL url = new URL(SERVICE_URL);
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
// Read the JSON data into the StringBuilder
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
json.append(buff, 0, read);
}
} catch (IOException e) {
Log.e(LOG_TAG, "Error connecting to service", e);
throw new IOException("Error connecting to service", e);
} finally {
if (conn != null) {
conn.disconnect();
}
}
// Must run this on the UI thread since it's a UI operation.
runOnUiThread(new Runnable() {
public void run() {
try {
createMarkersFromJson(json.toString());
} catch (JSONException e) {
Log.e(LOG_TAG, "Error processing JSON", e);
}
}
});
}
void createMarkersFromJson(String json) throws JSONException {
JSONArray jsonArray = new JSONArray(json);
List<Marker> markers = new ArrayList<Marker>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObj = jsonArray.getJSONObject(i);
Marker marker = mapB.addMarker(new MarkerOptions()
.title(jsonObj.getString("business_name"))
.position(new LatLng(
jsonObj.getJSONArray("latlng").getDouble(0),
jsonObj.getJSONArray("latlng").getDouble(2)
))
);
markers.add(marker);
}
}
}
我从我的网址输出的JSON
my JSON output from my url
[{"business_name":"Wine Bar","latlng":["43.6894658949280400","-116.3533687591552700"],
"business_id":"2","distance":"23.0298400562551"},
{"business_name":"Apple Headquarters","latlng":["37.3324083200000000","-122.0304781500000000"],
"business_id":"3","distance":"23.0298400562551"}]
我的logcat(我不知道如何来拉动整个日志猫,但这些都是错误)
my Logcat (I do not know how to pull the whole log cat but these are the errors)
08-21 00:00:27.371: E/JsOn ErRoR(357): at com..ReadComments.createMarkersFromJson(ReadComments.java:127)
08-21 00:00:27.371: E/JsOn ErRoR(357): at com..ReadComments$2.run(ReadComments.java:107)
部分截图
推荐答案
我已经得到了正确的code在这里它的工作完美。它已被更新要到当前的位置,因为我一直在玩弄它,因为修复。
I've Got the right code here its working perfect.it has been updated to go to the current location as well because I've been messing with it since the fix.
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Dialog;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class GetLocalBus extends FragmentActivity implements LocationListener {
private static final String LOG_TAG = "JsOn ErRoR";
private static final String SERVICE_URL = "";
protected GoogleMap mapB;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.get_local);
setUpMapIfNeeded();
// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
// Showing status
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 the SupportMapFragment of activity_main.xml
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapB);
// Getting GoogleMap object from the fragment
mapB = fm.getMap();
// Enabling MyLocation Layer of Google Map
mapB.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
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
}
}
@Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (mapB == null) {
mapB = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapB))
.getMap();
if (mapB != null) {
setUpMap();
}
}
}
private void setUpMap() {
new Thread(new Runnable() {
public void run() {
try {
retrieveAndAddCities();
} catch (IOException e) {
Log.e(LOG_TAG, "Cannot retrive cities", e);
return;
}
}
}).start();
}
protected void retrieveAndAddCities() throws IOException {
HttpURLConnection conn = null;
final StringBuilder json = new StringBuilder();
try {
// Connect to the web service
URL url = new URL(SERVICE_URL);
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
// Read the JSON data into the StringBuilder
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
json.append(buff, 0, read);
}
} catch (IOException e) {
Log.e(LOG_TAG, "Error connecting to service", e);
throw new IOException("Error connecting to service", e);
} finally {
if (conn != null) {
conn.disconnect();
}
}
// Must run this on the UI thread since it's a UI operation.
runOnUiThread(new Runnable() {
public void run() {
try {
createMarkersFromJson(json.toString());
} catch (JSONException e) {
Log.e(LOG_TAG, "Error processing JSON", e);
}
}
});
}
void createMarkersFromJson(String json) throws JSONException {
JSONArray jsonArray = new JSONArray(json);
System.out.print(json);
List<Marker> markers = new ArrayList<Marker>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObj = jsonArray.getJSONObject(i);
System.out.print(jsonObj.getJSONArray("latlng"));
Marker marker = mapB.addMarker(new MarkerOptions()
.title(jsonObj.getString("business_name"))
.position(new LatLng(
jsonObj.getJSONArray("latlng").getDouble(0),
jsonObj.getJSONArray("latlng").getDouble(1)))
.icon(BitmapDescriptorFactory.fromResource(R.drawable.graphic_map_icon))
);
markers.add(marker);
}
}
@Override
public void onLocationChanged(Location location) {
// Getting latitude of the current location
double latitude = location.getLatitude();
// Getting longitude of the current location
double longitude = location.getLongitude();
// Creating a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
// Showing the current location in Google Map
mapB.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
mapB.animateCamera(CameraUpdateFactory.zoomTo(15));
}
@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
}
}
另外这里是PHP
Also here is the PHP
<?php
if
(isset($_GET['lat']) && isset($_GET['lon'])&& isset($_GET['dist'])){
//make a simple database connection
$db = new mysqli();
$lat = $_GET['lat'];
$lon = $_GET['lon'];
$dist = $_GET['dist'];
$search_sql = "SELECT business_id, business_name, CONCAT_WS(\",\",business_lat, business_lon) AS latlng, ( 3959 * acos( cos( radians(37) ) * cos( radians( " . $lat . " ) ) * cos( radians( " . $lon . " ) - radians(-122) ) + sin( radians(37) ) * sin( radians( " . $lat . " ) ) ) ) AS distance
FROM somewhere HAVING distance < " . $dist . " ORDER BY distance LIMIT 0 , 20";
$search_results = $db->query($search_sql);
if($search_results->num_rows){
while ($row = $search_results->fetch_assoc())
{
$return_data[] = array(
'business_name' => $row['business_name'],
'latlng' => explode(',', $row['latlng']),
'business_id' => $row['business_id'],
'distance' => $row['distance']
);
}//end while
}
else{
$return_data[] = array();
}//end if
}else{
$return_data[] = array();
}
$bd_json = json_encode($return_data);
$db->close();
echo $bd_json;
?>
XML布局
xml layout
<fragment android:id="@+id/mapB"
android:layout_width="fill_parent"
android:layout_height="250.0dip"
android:layout_alignParentTop="true"
android:layout_centerInParent="true"
class="com.google.android.gms.maps.SupportMapFragment"
xmlns:android="http://schemas.android.com/apk/res/android" />
<TextView
android:id="@+id/TextView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/mapB" />
</RelativeLayout>
这篇关于创建一个从JSON数组PHP的MySQL的谷歌地图V2机器人标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!