0

我对 Android 和一般编程非常陌生。我正在开发一个 Android 应用程序,允许用户在谷歌地图上放置一个标记,一旦放置了标记,它的位置(纬度和经度)将被上传到存储在服务器上的外部 MySQL 数据库中。

我按照这些教程系列使我的 Google 地图在 Android 上正常工作:

谷歌地图教程

现在我希望能够将纬度和经度上传到我的数据库,但我不知道该怎么做。

这是我现在拥有的代码:

public class Main extends MapActivity implements LocationListener{
/** Called when the activity is first created. */

//set variables
MapView map; //set map to mapview
long start; //create a starting point when the user presses down on the map
long stop; //create a stop point when the user stops pressing down on the map
MapController controller; //create a map controller that animates where the user is going through the map activity
int x, y; //x and y position on the overlay when the user touches the screen
GeoPoint touchedPoint; //create a geopoint as touchedPoint
Drawable d; //create drawable item
List<Overlay> overlayList; //setup list of overlays
LocationManager lm; //setup location manager
String towers; //setup string called towers
int lat; //create lattitude for the phone's current position
int longi; //create longitude for the phone's current position
private ArrayList<ToDoItem> todoItems;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    map = (MapView)findViewById(R.id.mvMain);//set map to mapview in the main.xml
    map.setBuiltInZoomControls(true);//zoom function


    Touchy t = new Touchy();//new instance of touchy class
    overlayList = map.getOverlays();//list of overlays
    overlayList.add(t);//add touchy instance (t) to a list of overlays
    controller = map.getController();//setup controller
    GeoPoint point = new GeoPoint(51643234, 7848593);//setup geopoint
    controller.animateTo(point);//animate controller to that location
    controller.setZoom(6);//set zoom level

    //create drawable item and its location
    d = getResources().getDrawable(R.drawable.yellow);

    //Placing marker at location
    //retrieve location manager for controlling the location updates 
    lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Criteria crit = new Criteria();//setup criteria


    towers = lm.getBestProvider(crit, false);//return the provider that best fits the given criteria
    Location location = lm.getLastKnownLocation(towers);//access location through location manager and get the last known location called towers

    if (location != null){
        lat = (int) (location.getLatitude() *1E6);//get latitude
        longi = (int) (location.getLongitude() *1E6);//get longitude
        //add overlay to the list
        GeoPoint ourLocation = new GeoPoint(lat, longi);//setup geopoint as ourLocation with lat and long
        OverlayItem overlayItem = new OverlayItem(ourLocation, "Hello", "2nd String");//pass in outLocation to OverlayItem
        CustomMarker custom = new CustomMarker(d, Main.this);
        custom.insertPinpoint(overlayItem);
        overlayList.add(custom);
    }else{
        Toast.makeText(Main.this, "Couldn't find provider", Toast.LENGTH_SHORT).show();
    }

}

@Override
protected void onPause(){
    super.onPause();
    //when pause is pressed remove location updates
    lm.removeUpdates(this);
}

@Override
protected void onResume(){
    super.onResume();
    //when the resume is pressed request location updates
    lm.requestLocationUpdates(towers, 500, 1, this);
}

@Override
protected boolean isRouteDisplayed() {
    // TODO Auto-generated method stub
    return false;
}


//overlay class that handles all touch events
class Touchy extends Overlay{
    public boolean onTouchEvent(MotionEvent e, MapView m){ //onTouchEvent method which includes a motion even and a map view
    if(e.getAction() == MotionEvent.ACTION_DOWN){ //when the user presses down on the overlay
        start = e.getEventTime();//start point when the event happens 
        x = (int) e.getX();//x and y coordinates based on where the user touched the overlay
        y = (int) e.getY();
        touchedPoint = map.getProjection().fromPixels(x, y);//sets a geopoint based on where the user has touched on the screen. Relates the map activity to the user's actual touch on the overlay

    }
    if (e.getAction() == MotionEvent.ACTION_UP){ //when the user stops pressing down on the overlay
        stop = e.getEventTime();//stop point when the event happens
    }
    if (stop - start > 1500){ //if the user presses on the overlay for more than 1.5 seconds
        AlertDialog alert = new AlertDialog.Builder(Main.this).create();//setup alert dialog for the Main class
        alert.setTitle("Pick an Option");//set the title for the alert
        alert.setMessage("Please pick an option");//set the message for the alert


        //BUTTON 1
        //set a button for the alert. Refer to a dialogue interface for this OnClickListener
        alert.setButton("Place a Marker", new DialogInterface.OnClickListener() {

            //when the button is clicked
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub

                OverlayItem overlayItem = new OverlayItem(touchedPoint, "Hello", "2nd String");//setup overlay item and refer to touchedPoint which is geopoint
                CustomMarker custom = new CustomMarker(d, Main.this);//setup a custom marker with a "d" in the Main class
                custom.insertPinpoint(overlayItem);//add an overlayItem to the pinpoint array list
                overlayList.add(custom);//add custom overlay to the overlay list
                map.invalidate();//make MapView draw itself
                SaveRemote();
            }
        });

这不是我程序中的所有代码,但我尝试包含与我的问题相关的所有内容,并且可能会帮助您解决它。

如果您向下滚动到“按钮 1”,您可以看到我编写的代码,它在用户按下的位置放置了一个标记。在 Button 1 代码的最后,我调用了一个方法 SaveRemote,该方法负责根据标记的放置位置保存实际的纬度和经度。

我不知道在这个方法中放什么以及如何将它连接到我的主程序并从用户按下的位置获取实际的纬度和经度。

这是我编写的方法的代码

public void SaveRemote(){

      String result = "";

         InputStream is = null;
         try{
             HttpClient httpclient = new DefaultHttpClient();
             HttpPost httppost = new HttpPost("myservername.com/insert.php");

             ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();


              }catch(Exception e){
                 Log.e("log_tag", "Error in http connection"+e.toString());
            }
          }

如您所见,我在服务器上调用 insert.php 文件,该文件运行插入查询,将标记的纬度和经度添加到数据库中。

这是实际的 insert.php 代码:

 $con = mysql_connect("localhost","username","password");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("mydatabase", $con);

$result = mysql_query("INSERT INTO markers (lat, lng) VALUES (lat, lng)";

mysql_close($con);

我非常感谢您的帮助,因为我不知道如何将标记的位置发送到 SaveRemote 方法,该方法又会将这些数据发送到 php 文件。

谢谢

4

1 回答 1

0

嘿,我可能有点晚了,但你可以使用 setOnMarkerDragListener 解决这个问题,如下所示:

          map.setOnMarkerDragListener(new GoogleMap.OnMarkerDragListener() {
                @Override
                public void onMarkerDragStart(Marker marker) {
                    //Toast.makeText(TerminosYC.this.getActivity(), "Arrastra el marcador, hasta el lugar deseado",
                    //        Toast.LENGTH_SHORT).show();
                    LatLng position = marker.getPosition();
                    map.animateCamera(CameraUpdateFactory.newLatLngZoom(
                            new LatLng(position.latitude, position.longitude), 15));
                }

                @Override
                public void onMarkerDrag(Marker marker) {
                      //       System.out.println("Arrastrando...");
                    LatLng position = marker.getPosition();
                    map.animateCamera(CameraUpdateFactory.newLatLngZoom(
                            new LatLng(position.latitude, position.longitude), 15));
                }

                @Override
                public void onMarkerDragEnd(Marker marker) {
                    LatLng position = marker.getPosition();
                    latitudeeeee = position.latitude;
                    longitudeeee = position.longitude;
                    //Toast.makeText(
                    //        TerminosYC.this.getActivity(),
                    //        "Lat " + position.latitude + " "
                    //                + "Long " + position.longitude,
                    //        Toast.LENGTH_LONG).show();


                    //map.animateCamera(CameraUpdateFactory.newLatLngZoom(
                    //        new LatLng(position.latitude, position.longitude), 15));

                }
            });

        }
    });
于 2017-04-14T03:43:24.177 回答