通过经纬度获得地址与城市名称

 更新时间:2016年9月20日 20:01  点击:1774
本文章介绍了关于在android开发中通过经纬度获得地址与城市名称,大部分文章是通过cvs来获得,比较简单,有些信息没有,所以修改了一下如下方法

 

具体调用方式如下:

      

 代码如下 复制代码

            jaddrobj = GetJsonAddr(String.valueOf(dLat),

String.valueOf(dLong));

if (jaddrobj==null) {

jaddrobj = SysUtil.GetJsonAddr(String.valueOf(dLat),

String.valueOf(dLong));

}

if (jaddrobj!=null) {

jsobj = jaddrobj.getJSONObject("Status");

if(jsobj.getString("code").equals("200")){

jplacearr = jaddrobj.getJSONArray("Placemark");

jplaceobj = jplacearr.getJSONObject(0);

address = jplaceobj.getString("address");

grobaldata.myAddress = address;// 当前地址放到全局变量里

   grobaldata.curAddress = address;// 当前地址放到全局变量里

   city = jplaceobj.getJSONObject("AddressDetails").getJSONObject("Country")

    .getJSONObject("AdministrativeArea").getJSONObject("Locality")

    .getString("LocalityName");

}

else {

rtValue = "error";

}

}

/**

* 根据经纬度反向解析地址,有时需要多尝试几次

* 注意:(摘自:http://code.google.com/intl/zh-CN/apis/maps/faq.html

* 提交的地址解析请求次数是否有限制?) 如果在 24 小时时段内收到来自一个 IP 地址超过 2500 个地址解析请求, 或从一个 IP

* 地址提交的地址解析请求速率过快,Google 地图 API 编码器将用 620 状态代码开始响应。 如果地址解析器的使用仍然过多,则从该

 代码如下 复制代码

* IP 地址对 Google 地图 API 地址解析器的访问可能被永久阻止。

*

* @param latitude

*            纬度

* @param longitude

*            经度

* @return JSONObject

*

* @author lvqiyong

*/

/*例子如下:

* {

 "name": "29.871398,121.5817",

 "Status": {

   "code": 200,

   "request": "geocode"

 },

 "Placemark": [ {

   "id": "p1",

   "address": "中国浙江省宁波市江东区中兴路360号 邮政编码: 315040",

   "AddressDetails": {

  "Accuracy" : 8,

  "Country" : {

     "AdministrativeArea" : {

        "AdministrativeAreaName" : "浙江省",

        "Locality" : {

           "DependentLocality" : {

              "DependentLocalityName" : "江东区",

              "Thoroughfare" : {

                 "ThoroughfareName" : "中兴路360号"

              }

           },

           "LocalityName" : "宁波市"

        }

     },

     "CountryName" : "中国",

     "CountryNameCode" : "CN"

  }

},

   "ExtendedData": {

     "LatLonBox": {

       "north": 29.8737610,

       "south": 29.8710630,

       "east": 121.5832290,

       "west": 121.5805310

     }

   },

   "Point": {

     "coordinates": [ 121.5818800, 29.8724120, 0 ]

   }

 } ]

}*/

public static JSONObject GetJsonAddr(String latitude, String longitude) {

 

// 也可以是http://maps.google.cn/maps/geo?output=csv&key=abcdef&q=%s,%s,不过解析出来的是英文地址

// 密钥可以随便写一个key=abc

// output=csv,也可以是xml或json,采用默认的方式是output=json

String url = String

.format(

"http://ditu.google.cn/maps/geo?key=abcdef&q=%s,%s",

latitude, longitude);

HttpGet httpGet = new HttpGet(url);

        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); 

            }*/

            HttpEntity entity = response.getEntity();

BufferedReader br = new BufferedReader(new InputStreamReader(entity

.getContent()));

String result = br.readLine();

while (result != null) {

stringBuilder.append(result);

result = br.readLine();

}

        } catch (ClientProtocolException e) { 

        } catch (IOException e) { 

        } 

 

        JSONObject jsonObject = new JSONObject(); 

        try { 

            jsonObject = new JSONObject(stringBuilder.toString()); 

        } catch (JSONException e) { 

            e.printStackTrace(); 

        } 

 

        return jsonObject; 

}

json数据格式解析我自己分为两种,一种是普通的,一种是带有数组形式的,下面积们分别举说明一下关于android手机开发中处理方法。

普通形式的:
服务器端返回的json数据格式如下:

 代码如下 复制代码

{"userbean":{"Uid":"100196","Showname":"u75afu72c2u7684u7334u5b50","Avtar":null,"State":1}}

分析代码如下:

 代码如下 复制代码

// TODO 状态处理 500 200
                int res = 0;
                res = httpClient.execute(httpPost).getStatusLine().getStatusCode();
                if (res == 200) {
                    /*
                     * 当返回码为200时,做处理
                     * 得到服务器端返回json数据,并做处理
                     * */
                    HttpResponse httpResponse = httpClient.execute(httpPost);
                    StringBuilder builder = new StringBuilder();
                    BufferedReader bufferedReader2 = new BufferedReader(
                            new InputStreamReader(httpResponse.getEntity().getContent()));
                    String str2 = "";
                    for (String s = bufferedReader2.readLine(); s != null; s = bufferedReader2
                            .readLine()) {
                        builder.append(s);
                    }
                    Log.i("cat", ">>>>>>" + builder.toString());

JSONObject jsonObject = new JSONObject(builder.toString())
                        .getJSONObject("userbean");

                String Uid;
                String Showname;
                String Avtar;
                String State;

                Uid = jsonObject.getString("Uid");
                Showname = jsonObject.getString("Showname");
                Avtar = jsonObject.getString("Avtar");
                State = jsonObject.getString("State");

带数组形式的:
服务器端返回的数据格式为:

 代码如下 复制代码
{"calendar":
    {"calendarlist":
            [
            {"calendar_id":"1705","title":"(u4eb2u5b50)ddssd","category_name":"u9ed8u8ba4u5206u7c7b","showtime":"1288927800","endshowtime":"1288931400","allDay":false},
            {"calendar_id":"1706","title":"(u65c5u884c)","category_name":"u9ed8u8ba4u5206u7c7b","showtime":"1288933200","endshowtime":"1288936800","allDay":false}
            ]
    }
}

分析代码如下:

 代码如下 复制代码
// TODO 状态处理 500 200
                int res = 0;
                res = httpClient.execute(httpPost).getStatusLine().getStatusCode();
                if (res == 200) {
                    /*
                     * 当返回码为200时,做处理
                     * 得到服务器端返回json数据,并做处理
                     * */
                    HttpResponse httpResponse = httpClient.execute(httpPost);
                    StringBuilder builder = new StringBuilder();
                    BufferedReader bufferedReader2 = new BufferedReader(
                            new InputStreamReader(httpResponse.getEntity().getContent()));
                    String str2 = "";
                    for (String s = bufferedReader2.readLine(); s != null; s = bufferedReader2
                            .readLine()) {
                        builder.append(s);
                    }
                    Log.i("cat", ">>>>>>" + builder.toString());
                    /**
                     * 这里需要分析服务器回传的json格式数据,
                     */
                    JSONObject jsonObject = new JSONObject(builder.toString())
                            .getJSONObject("calendar");
                    JSONArray jsonArray = jsonObject.getJSONArray("calendarlist");
                    for(int i=0;i<jsonArray.length();i++){
                        JSONObject jsonObject2 = (JSONObject)jsonArray.opt(i);
                        CalendarInfo calendarInfo = new CalendarInfo();
                        calendarInfo.setCalendar_id(jsonObject2.getString("calendar_id"));
                        calendarInfo.setTitle(jsonObject2.getString("title"));
                        calendarInfo.setCategory_name(jsonObject2.getString("category_name"));
                        calendarInfo.setShowtime(jsonObject2.getString("showtime"));
                        calendarInfo.setEndtime(jsonObject2.getString("endshowtime"));
                        calendarInfo.setAllDay(jsonObject2.getBoolean("allDay"));
                        calendarInfos.add(calendarInfo);
                    }

总结,普通形式的只需用JSONObject ,带数组形式的需要使用JSONArray 将其变成一个list。

本文章介绍了一个关于android通过http来实现文件上传功能,在服务器端我们是用php来实现的,有需要的朋友可以参考一下
 代码如下 复制代码

 

<?php

///如果有上传文件则接收

if($_FILES){  

$target_path = $target_path . basename( $_FILES['file1']['name']);

 try{ if(move_uploaded_file($_FILES['file1']['tmp_name'], $target_path)) { 

echo "The file ".  basename( $_FILES['file1']['name']).  " has been uploaded"; 

}

} catch( Exception $e ) { 

echo $e->getMessage();   } 

}

?>

Android 代码:

package com.nbcio.baishicha.test;
import java.io.DataOutputStream;

import java.io.FileInputStream;

import java.io.IOException;

import java.io.InputStream;

import java.net.HttpURLConnection;

import java.net.URL;

import android.app.Activity;

import android.content.Intent;

import android.os.Bundle;

import android.widget.Toast; 


public class test extends Activity {

/*

* 变量声明 newName:上传后在服务器上的文件名称

*

* uploadFile:要上传的文件路径 actionUrl:服务器对应的程序路径

*/

private String newName = "";

private String uploadFile = "";

private String actionUrl = "http://www.111cn.net/index.php";//这里定义你的上传路径 


@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
Intent intent = this.getIntent();

Bundle bundle = intent.getExtras();

newName = bundle.getString("fileName");

uploadFile = newName;
try {

String ok = post(actionUrl, newName);

Toast.makeText(this, "OK!", Toast.LENGTH_LONG).show();

finish(); 


} catch (IOException e) {

//

// TODO Auto-generated catch block

e.printStackTrace();

}



/* 上传文件到Server的方法 */

/**

*

* @param actionUrl

* @param params

* @param files

* @return

* @throws IOException

*/

public static String post(String actionUrl, String FileName)

throws IOException { 


String BOUNDARY = java.util.UUID.randomUUID().toString();

String PREFIX = "--", LINEND = "rn";

String MULTIPART_FROM_DATA = "multipart/form-data";

String CHARSET = "UTF-8";

 


URL uri = new URL(actionUrl);

HttpURLConnection conn = (HttpURLConnection) uri.openConnection();

conn.setReadTimeout(5 * 1000);

// 缓存的最长时间

conn.setDoInput(true);// 允许输入

conn.setDoOutput(true);// 允许输出

conn.setUseCaches(false); // 不允许使用缓存

conn.setRequestMethod("POST");

conn.setRequestProperty("connection", "keep-alive");

conn.setRequestProperty("Charsert", "UTF-8");

conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA

+ ";boundary=" + BOUNDARY);

 


DataOutputStream outStream = new DataOutputStream(

conn.getOutputStream());

 


// 发送文件数据

if (FileName != "") {

 


StringBuilder sb1 = new StringBuilder();

sb1.append(PREFIX);

sb1.append(BOUNDARY);

sb1.append(LINEND);

sb1.append("Content-Disposition: form-data; name="file1"; filename=""

+ FileName + """ + LINEND);

sb1.append("Content-Type: application/octet-stream; charset="

+ CHARSET + LINEND);

sb1.append(LINEND);

outStream.write(sb1.toString().getBytes());

 


InputStream is = new FileInputStream(FileName);

byte[] buffer = new byte[1024];

int len = 0;

while ((len = is.read(buffer)) != -1) {

outStream.write(buffer, 0, len);

}

 
is.close();

outStream.write(LINEND.getBytes());

 
}

 
// 请求结束标志

byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();

outStream.write(end_data);

outStream.flush();

 
// 得到响应码

int res = conn.getResponseCode();

InputStream in = null;

if (res == 200) {

in = conn.getInputStream();

int ch;

StringBuilder sb2 = new StringBuilder();

while ((ch = in.read()) != -1) {

sb2.append((char) ch);

}

}

return in == null ? null : in.toString();

}

}

发一个异步图片加载控件。网上也有大把的异步网络加载图片的控件,但是有一个问题,异步加载会造成列表中的图片混乱,因为列表的每一项的View都可能被重用,异步加载的时候多个异步线程引用到了同一个View将造成图片加载错乱。该控件解决这个问题
 代码如下 复制代码

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.AttributeSet;
import android.widget.ImageView;

/**
 * 异步图片控件
 * 使用:new AsyncImageView().asyncLoadBitmapFromUrl("http://xxxx","缓存路径"){
 *
 * @author gaoomei@gmail.com
 * @site http://obatu.sinaapp.com
 * @version 1.0
 * @2011-12-3
 */
public class AsyncImageView extends ImageView {

 /**
  * 异步task加载器
  */
 private AsyncLoadImage mAsyncLoad;

 /**
  * 下载回来的图片缓存存活时间,单位:秒(s),默认30分钟
  */
 private long mCacheLiveTime = 1800;

 public AsyncImageView(Context context) {
  super(context);
 }

 public AsyncImageView(Context context, AttributeSet attrs) {
  super(context, attrs);
 }

 public AsyncImageView(Context context, AttributeSet attrs, int defStyle) {
  super(context, attrs, defStyle);
 }

 /**
  *
  */
 @Override
 public void setImageDrawable(Drawable drawable) {
  if (mAsyncLoad != null) {
   mAsyncLoad.cancel(true);
   mAsyncLoad = null;
  }
  super.setImageDrawable(drawable);
 }

 /**
  * 重写下面几个设置图片资源的方法,目地是取消网络加载
  */
 @Override
 public void setImageResource(int resId) {
  cancelLoad();
  super.setImageResource(resId);
 }

 @Override
 public void setImageURI(Uri uri) {
  cancelLoad();
  super.setImageURI(uri);
 }

 @Override
 public void setImageBitmap(Bitmap bitmap) {
  cancelLoad();
  super.setImageBitmap(bitmap);
 }

 /**
  * 取消正在进行的异步task
  */
 public void cancelLoad() {
  if (mAsyncLoad != null) {
   mAsyncLoad.cancel(true);
   mAsyncLoad = null;
  }
 }

 /**
  * 设置图片存活时间
  *
  * @param second
  *            存活时间,单位【秒】,如果等于0或null,则不缓存
  */
 public void setCacheLiveTime(long second) {
  if (second == 0) {
   this.mCacheLiveTime = 0;
  } else if (second >= 0) {
   this.mCacheLiveTime = second * 1000;
  }
 }

 /**
  * 从网络异步加载
  *
  * @param url
  * @param saveFileName
  */
 public void asyncLoadBitmapFromUrl(String url, String saveFileName) {
  if (mAsyncLoad != null) {
   mAsyncLoad.cancel(true);
  }
  // AsyncTask不可重用,所以每次重新实例
  mAsyncLoad = new AsyncLoadImage();
  mAsyncLoad.execute(url, saveFileName);
 }

 /**
  * 异步加载器
  */
 private class AsyncLoadImage extends AsyncTask {
  /**
   * 是否取消
   */
  private boolean isCancel = false;

  @Override
  protected Bitmap doInBackground(String... params) {
   if (isCancel) {
    return null;
   }
   String url = params[0];
   String fileName = params[1];
   try {
    return getBitmap(url, fileName);
   } catch (IOException e) {
    e.printStackTrace();
   }
   return null;
  }

  @Override
  protected void onCancelled() {
   System.out.println("async load imgae cancel");
   isCancel = true;
  }

  @Override
  protected void onPostExecute(Bitmap result) {
   if (!isCancel && result != null) {
    AsyncImageView.this.setImageBitmap(result);
   }
  }
 }

 /**
  * 下载图片
  *
  * @param urlString
  *            url下载地址
  * @param fileName
  *            缓存文件路径
  * @throws IOException
  */
 private Bitmap getBitmap(String urlString, String fileName)
   throws IOException {
  if (fileName == null || fileName.trim().isEmpty()) {
   InputStream input = getBitmapInputStreamFromUrl(urlString);
   return BitmapFactory.decodeStream(input);
  }

  File file = new File(fileName);
  if (!file.isFile()
    || (mCacheLiveTime > 0 && (System.currentTimeMillis()
      - file.lastModified() > mCacheLiveTime))) {
   InputStream input = getBitmapInputStreamFromUrl(urlString);
   file = saveImage(input, fileName);
   // 如果文件结构创建失败,则直接从输入流解码图片
   if (file == null || !file.exists() || !file.canWrite()
     || !file.canRead()) {
    return BitmapFactory.decodeStream(input);
   }
  }
  return BitmapFactory.decodeFile(file.getAbsolutePath());
 }

 /**
  * 下载图片,输入InputStream
  *
  * @param urlString
  * @return
  * @throws IOException
  */
 private InputStream getBitmapInputStreamFromUrl(String urlString)
   throws IOException {
  URL url = new URL(urlString);
  URLConnection connection = url.openConnection();
  connection.setConnectTimeout(25000);
  connection.setReadTimeout(90000);
  return connection.getInputStream();
 }

 /**
  * 从输入流保存图片到文件系统
  *
  * @param fileName
  * @param input
  * @return
  */
 private File saveImage(InputStream input, String fileName) {
  if (fileName.trim().isEmpty() || input == null) {
   return null;
  }
  File file = new File(fileName);
  OutputStream output = null;
  try {
   file.getParentFile().mkdirs();
   if (file.exists() && file.isFile()) {
    file.delete();
   }
   if (!file.createNewFile()) {
    return null;
   }
   output = new FileOutputStream(file);
   byte[] buffer = new byte[4 * 1024];
   do {
    // 循环读取
    int numread = input.read(buffer);
    if (numread == -1) {
     break;
    }
    output.write(buffer, 0, numread);
   } while (true);
   output.flush();
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   try {
    output.close();
   } catch (IOException e) {
    e.printStackTrace();
   } catch (Exception e2) {
    e2.printStackTrace();
   }
  }
  return file;
 }
}

本文章分享一篇关于android与Web服务器交互时的cookie使用实例有需要的同学可以参考一下。

下面是具体的代码
/**

* 向网站发送get请求,url需按照api要求写,返回取得的信息。

* //这个专门给大众点评传入cookie参数用,目的是为了获得用户选择的城市信息

* @param url

* @param client

* @return String

* @author lvqiyong

*/

 代码如下 复制代码

public static String getRequest1(String url, DefaultHttpClient client,

String charset) throws Exception {

String result = null;

int statusCode = 0;

HttpGet getMethod = new HttpGet(url);

Log.d(TAG, "do the getRequest,url=" + url + "");

try {

getMethod.setHeader("User-Agent", USER_AGENT);

getMethod.setHeader("Cookie", "cy=" + value);//这个专门给大众点评传入cookie参数用,目的是为了获得用户选择的城市信息

// 添加用户密码验证信息

// client.getCredentialsProvider().setCredentials(

// new AuthScope(null, -1),

// new UsernamePasswordCredentials(mUsername, mPassword));

 

HttpResponse httpResponse = client.execute(getMethod);

// statusCode == 200 正常

statusCode = httpResponse.getStatusLine().getStatusCode();

Log.d(TAG, "statuscode = " + statusCode);

// 处理返回的httpResponse信息

if (statusCode == 200) {

result = retrieveInputStream(httpResponse.getEntity(), charset);

Cookie cookie;

String cookname,cookvalue;

List<Cookie> cookies = client.getCookieStore().getCookies();

if (cookies.isEmpty()) {

Log.i(TAG, "-------Cookie NONE---------");

} else {

for (int i = 0; i < cookies.size(); i++) {

// 保存cookie

cookie = cookies.get(i);

cookname = cookie.getName().trim();

cookvalue = cookie.getValue().trim();

if(cookname.equals("cy")){

name = cookname;

value = cookvalue;

}

}

}

} else

result = "networkerror";

} catch (ConnectTimeoutException e) {// 超时或网络连接出错

result = "timeouterror";

// e.printStackTrace();

} catch (ClientProtocolException e) {

result = "networkerror";

// e.printStackTrace();

} catch (Exception e) {

result = "readerror";

Log.e(TAG, e.getMessage());

throw new Exception(e);

} finally {

getMethod.abort();

}

return result;

}

[!--infotagslink--]

相关文章