package com.hys.app.service.kuaidiniao;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import com.google.protobuf.ServiceException;
import com.hys.app.service.kuaidiniao.entity.LongitudeLatitude;
import org.json.JSONObject;

public class GaoDeUtil {
    private static final String GAODE_GEOCODE_API = "http://restapi.amap.com/v3/geocode/geo?key=%s&address=%s";
    private static final String API_KEY = "c2f5532f8238a3523a9f381cb3e630c8";

    public static  LongitudeLatitude getLongitudeLatitude(String location) {
        LongitudeLatitude longitudeLatitude = new LongitudeLatitude();
        try {
            String geocodeApi = String.format(GAODE_GEOCODE_API, API_KEY, java.net.URLEncoder.encode(location, "UTF-8"));

            URL url = new URL(geocodeApi);
            URLConnection connection = url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuilder content = new StringBuilder();
            while ((inputLine = in.readLine()) != null) {
                content.append(inputLine);
            }
            in.close();

            JSONObject jsonObject = new JSONObject(content.toString());
            if ("1".equals(jsonObject.getString("status"))) {
                JSONObject geocodes = jsonObject.getJSONArray("geocodes").getJSONObject(0);
                String location1 = geocodes.getString("location");
                String[] locations = location1.split(",");
                double longitude =Double.valueOf(locations[0]) ;
                double latitude =Double.valueOf(locations[1]) ;
                longitudeLatitude.setLongitude(String.valueOf(longitude));
                longitudeLatitude.setLatitude(String.valueOf(latitude));
            } else {
                throw new ServiceException("位置解析失败，错误码：" + jsonObject.getString("infocode"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return longitudeLatitude;
    }
}
