简体   繁体   English

如何从Web服务动态获取Google地图(map_icon,标题,纬度,经度)

[英]How to get Google map (map_icon, title, latitude, longitude) dynamically from webservice

This is my web service 这是我的网络服务

where I want to get map_icon, longitude, latitude dynamically from given web service. 我想从给定的Web服务动态获取map_icon,经度,纬度。 I am stuck at this point. 我被困在这一点上。 How can I do this please help me out. 我该怎么做,请帮帮我。 In old code what is done is get longitude, latitude, post_title from web service on the basis of id and then assign image statically. 在旧代码中,要做的是基于id从Web服务获取经度,纬度和post_title,然后静态分配图像。


Frnt_mapActivity.java Frnt_mapActivity.java

public class Frnt_mapActivity extends Activity {

public String Shop_title;
public String Shop_address;
public String Shop_icons;
ProgressDialog mDialog;
JSONObject jsonobject3;
JSONArray jsonarray3;
// Google Map
private static GoogleMap googlemap;
public static ArrayList<SearchBeams> searchdata_list;
public static ArrayList<NormalSearchBeams> normlSearchList;
ArrayList<All_products_lat_long> venueList;

private int i;
private Intent intent;
HashMap<Marker, Integer> hashMap=new HashMap<Marker, Integer>();
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.frnt_map_activity);

    googlemap=((MapFragment)getFragmentManager().findFragmentById(R.id.places_map)).getMap();
    googlemap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    googlemap.setMyLocationEnabled(true);
    googlemap.getUiSettings().setZoomControlsEnabled(true);
    googlemap.getUiSettings().setMyLocationButtonEnabled(true);
    googlemap.getUiSettings().setCompassEnabled(true);
    googlemap.getUiSettings().setRotateGesturesEnabled(true);
    googlemap.getUiSettings().setZoomGesturesEnabled(true);
    googlemap.setMyLocationEnabled(true);
    intent=new Intent(Frnt_mapActivity.this,MainActivity.class);
    googlemap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {

        @Override
        public void onInfoWindowClick(Marker arg0) {
            i=hashMap.get(arg0);
            intent.putExtra("PRODUCT_ID", venueList.get(i).getId());
            startActivity(intent);
            //overridePendingTransition( R.anim.slide_right, R.anim.slide_left );
        }
    });


    new Frnt_mIcons_Activity().execute();


}

class AddMarkerAsyncTask extends AsyncTask<String,String,String>{

    private All_products_lat_long venue;
    private int k;
    BitmapDescriptor bd=null;

    AddMarkerAsyncTask(All_products_lat_long venue,int k){
        this.venue=venue;
        this.k=k;
    }




    @Override
    protected String doInBackground(String... strings) {
        try{
            bd=BitmapDescriptorFactory.fromBitmap(Glide.
                    with(Frnt_mapActivity.this).
                    load(venue.getMap_icon()).
                    asBitmap().
                    into(100, 100). // Width and height
                    get());
        }catch (Exception e){
            bd=null;
            e.printStackTrace();

        }

        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);

        try{
            if(bd!=null){
                Marker marker=googlemap.addMarker(new MarkerOptions()
                        .position(new LatLng(Double.parseDouble(venue.getLatitude()), Double.parseDouble(venue.getLongitude())))
                        .title(venue.getPost_title())
                        .icon(bd));
                hashMap.put(marker, k);
            }

        }catch (Exception e){
            e.printStackTrace();
        }


    }
}


private void addMarkers() {




    for(int k=0; k<venueList.size(); k += 1){

        //nirmal
        try{
            Log.e("nirmal",venueList.get(k).getMap_icon());

            //new AddMarkerAsyncTask(venueList.get(k),k).execute();

            double ln = Double.parseDouble(venueList.get(k).getLongitude());
            double la = Double.parseDouble(venueList.get(k).getLatitude());
                /*String title=venueList.get(k).getPost_title()==null?"":venueList.get(k).getPost_title();
                URL url = new URL(venueList.get(k).getMap_icon());
                Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
                BitmapDescriptor bd=BitmapDescriptorFactory.fromBitmap(image);*/


                /*Marker marker=googlemap.addMarker(new MarkerOptions()
                        .position(new LatLng(la, ln))
                        .title(title)
                        .icon(bd));
                hashMap.put(marker, k);*/

            switch (Integer.parseInt(venueList.get(k).getId()))
            {
                case 5689 :
                    Marker marker=googlemap.addMarker(new MarkerOptions()
                            .position(new LatLng(la, ln))
                            .title(venueList.get(k).getPost_title())
                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.fruitandveg)));
                    hashMap.put(marker, k);
                    break;
                case 5779 :
                    Marker marker1=googlemap.addMarker(new MarkerOptions()
                            .position(new LatLng(la, ln))
                            .title(venueList.get(k).getPost_title())
                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.coffee)));
                    hashMap.put(marker1, k);
                    break;
                case 5798 :
                    Marker marker3 = googlemap.addMarker(new MarkerOptions()
                            .position(new LatLng(la, ln))
                            .title(venueList.get(k).getPost_title())
                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.takeaway)));
                    hashMap.put(marker3, k);
                    break;
                case 5810 :
                    Marker marker4 = googlemap.addMarker(new MarkerOptions()
                            .position(new LatLng(la, ln))
                            .title(venueList.get(k).getPost_title())
                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.restaurant_steakhouse)));
                    hashMap.put(marker4, k);
                    break;
                case 6005 :
                    Marker marker5 = googlemap.addMarker(new MarkerOptions()
                            .position(new LatLng(la, ln))
                            .title(venueList.get(k).getPost_title())
                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.clambers_playcentre)));
                    hashMap.put(marker5, k);
                    break;
                case 6011 :
                    Marker marker6 = googlemap.addMarker(new MarkerOptions()
                            .position(new LatLng(la, ln))
                            .title(venueList.get(k).getPost_title())
                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.thetruecrimemuseum)));
                    hashMap.put(marker6, k);

                    break;
                .........
                ...........
                ............
                default :
                    break;
            }

        }catch (Exception e){
            Log.e("addMarkers",k+"");
            e.printStackTrace();
        }


    }
}

/******************FOR MAP******************/
class Frnt_mIcons_Activity extends AsyncTask<String, String, String> {

    public ArrayList<All_products_lat_long> maplist;


    @Override
    protected void onPreExecute() {
        mDialog = new ProgressDialog(Frnt_mapActivity.this);
        mDialog.setMessage("Loading...");
        mDialog.setCancelable(false);
        mDialog.show();
        super.onPreExecute();
    }




    // Slow Implementation
    private String inputStreamToString(InputStream is) {
        String s = "";
        String line = "";
        // Wrap a BufferedReader around the InputStream
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        // Read response until the end
        try {
            while ((line = rd.readLine()) != null) {
                s += line;
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // Return full string
        return s;
    }


    @Override
    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub  
        maplist = new ArrayList<All_products_lat_long>();

        HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

        DefaultHttpClient client = new DefaultHttpClient();

        SchemeRegistry registry = new SchemeRegistry();
        SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
        socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
        registry.register(new Scheme("http", socketFactory, 443));
        SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
        DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams());



  // Set verifier
                HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
        HttpPost httpPost = new HttpPost("http://towncitycards.com/webservice_action.php?action=all_products");

        try{

            HttpResponse response = httpClient.execute(httpPost);
            String data = inputStreamToString(response.getEntity().getContent());
            jsonobject3 = new JSONObject(data);
            jsonarray3 = new JSONArray(jsonobject3.getString("all_products"));
            venueList =new ArrayList<All_products_lat_long>();
            for(int j=0; j<jsonarray3.length();j++){
                JSONObject itemobj = jsonarray3.getJSONObject(j);
                //SHOW SEARCH RESULT
                All_products_lat_long searchItems = new All_products_lat_long();

                searchItems.setId(itemobj.getString("ID"));
                searchItems.setPost_title(itemobj.getString("post_title"));
                searchItems.setMap_icon(itemobj.getString("map_icon"));
                searchItems.setLongitude(itemobj.getString("longitude"));
                searchItems.setLatitude(itemobj.getString("latitude"));
                //          System.out.println("######Ashish is object >>"+itemobj);
                venueList.add(searchItems);
                //      System.out.println("SEARCHLISTSS@@@@@@@"+venueList.get(j).getLongitude());
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }


    @Override
    public void onPostExecute(String result) {
        super.onPostExecute(result);

        //System.out.println("SEARCHLISTSS@@@@@@@"+venueList);
        //System.out.println("AAAAAAAAAAAAAAAAAAAAAAAAAAA"+venueList);
        try{
            if(venueList.size()>0)
            {
                addMarkers();
//              Toast.makeText(Frnt_mapActivity.this,"Search for the venue11.",Toast.LENGTH_SHORT).show();

            }
            else
                Toast.makeText(Frnt_mapActivity.this,"Search for the venue.",Toast.LENGTH_SHORT).show();
            //LatLng coordinate = new LatLng(22.75852160, 75.8911550);
            LatLng coordinate = new LatLng(50.85514, 0.58382);
            CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(coordinate, 18);
            googlemap.animateCamera(yourLocation);
            for (int i = 0; i < jsonarray3.length(); i++) {

                jsonobject3 = jsonarray3.getJSONObject(i);

                Shop_title = jsonobject3.optString("post_title");
                Shop_address = jsonobject3.optString("map_icon");
                Shop_icons = jsonobject3.optString("map_icon");
                //}
            }


        }catch(Exception e){
            e.printStackTrace();
        }

        if(mDialog!=null && mDialog.isShowing()){
            mDialog.dismiss();
        }
    }
}

} }

I dont Realy understand Your Question But 我真的不明白你的问题,但是

u can make 你可以做

Map<String, Marker> markerMap;

where String is your ID , or int as your want 其中String是您的ID,或者是您想要的int

then 然后

int your AsynTask to get JSON data 将您的AsynTask插入以获取JSON数据

 Marker marker = YOURMAP.addMarker(options);
                    marker.setTag(YOUR_ID);
                    //   markers.add(marker);
                    markerMap.put(YOUR_ID, marker);

where options is 选项在哪里

MarkerOptions options = new MarkerOptions();
                    options.position(YOUR_JSON_OBJECT.Latitude, YOUR_JSON_OBJECT.Longtite));
                    options.title(YOUR_TITLE);
                     options.visible(true);
                         options.icon(YOUR_IMAGE);

hope is`s help 希望是帮助

There are no icons for markers in Your server response JSON, just references for it. 您的服务器响应JSON中没有用于标记的图标,仅对其进行引用。 So You should: 因此,您应该:

1) download JSON response from Your "web service" (for example like in this question answers, but better use Service ); 1)从您的“ Web服务”中下载JSON响应(例如,类似于问题的答案,但最好使用Service );

2) for each "ID" of response get icon from URL, stored in "map_icon" field (for example like in that question answers) 2)对于响应的每个“ ID”,从URL获取图标,并将其存储在“ map_icon”字段中(例如,在问题的答案中)

3) create Google Maps marker with icon. 3)用图标创建Google Maps标记。 downloaded in p.2 like in Your "old code" or that . 在第2页中下载,就像您的“旧代码”中那样

Update 更新

There are several issues in Your task: 您的任务中有几个问题:

1) Your server response contains wrong URL's for "map_icon": http:// protocol prefix instead of https:// , so You should replace http:// with https:// ; 1)您的服务器响应中包含“ map_icon”的错误URL: http://协议前缀而不是https:// ,因此您应将http://替换为https://

2) some of "map_icon" URL's contains UNICODE symbols (like symbol Pound "£" in save£2.png ), so You should encode it to percent-encoded format: save%C2%A32.png instead of save£2.png ; 2)一些“ map_icon” URL包含UNICODE符号(例如save£2.png 2.png中的符号磅“£”),因此您应该将其编码为百分比编码格式: save%C2%A32.png而不是save£2.png ;

3) some of "map_icon" URL's even not exists (like 3)一些“ map_icon” URL甚至不存在(例如

https://towncitycards.com/wp-content/uploads/2015/01/googlemapicons/save50p.png or https://towncitycards.com/wp-content/uploads/2015/01/googlemapicons/information.png ) so You should ignore it (or set some default icon for it) https://towncitycards.com/wp-content/uploads/2015/01/googlemapicons/save50p.pnghttps://towncitycards.com/wp-content/uploads/2015/01/googlemapicons/information.png ),所以您应该忽略它(或为其设置一些默认图标)

So, according this, described above (before update) steps can be done with AsyncTask -based class, like this: 因此,据此,可以使用基于AsyncTask的类完成上述(更新之前)的步骤,如下所示:

protected class CreateProductListTask extends AsyncTask<Void, Void, List<Product>> {

    private String serverUrl;

    public CreateProductListTask(String url) {
        super();
        this.serverUrl = url;
    }

    @Override
    protected List<Product> doInBackground(Void... params)
    {

        URLConnection urlConn = null;
        BufferedReader bufferedReader = null;
        try
        {
            URL url = new URL(this.serverUrl);
            urlConn = url.openConnection();
            bufferedReader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));

            StringBuffer stringBuffer = new StringBuffer();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuffer.append(line);
            }

            JSONObject response = new JSONObject(stringBuffer.toString());

            List<Product> products = new ArrayList<>();
            HashMap<String, Bitmap> iconsMap = new HashMap<>();
            try {
                JSONArray productsJSON = response.getJSONArray("all_products");
                for (int ixProduct=0; ixProduct<productsJSON.length(); ixProduct++) {
                    JSONObject productJSON = productsJSON.getJSONObject(ixProduct);
                    String mapIconStr = productJSON.getString("map_icon");
                    URI uri = new URI(mapIconStr);
                    String[] segments = uri.getPath().split("/");
                    String iconName = segments[segments.length-1];

                    // percetn-encode URL
                    String mapIconPath = mapIconStr.substring(0, mapIconStr.indexOf(iconName));
                    String iconUrlString = mapIconPath + URLEncoder.encode(iconName, "UTF-8");

                    // replace "http:" with "https:"
                    iconUrlString = iconUrlString.replace("http:", "https:");

                    Bitmap bmp;
                    if (!iconsMap.containsKey(iconUrlString)) {
                        bmp = getBitmapFromURL(iconUrlString);
                        // populate map with unique icons
                        iconsMap.put(iconUrlString, bmp);
                    } else {
                        bmp = iconsMap.get(iconUrlString);
                    }

                    if (bmp != null) {
                        try {
                            Product product = new Product();
                            product.name = productJSON.getString("post_title");
                            product.lat = productJSON.getDouble("latitude");
                            product.lon = productJSON.getDouble("longitude");
                            product.icon = bmp;
                            products.add(product);
                        } catch (Exception ignore) {
                        }
                    }

                }

            } catch (JSONException ex) {
                Log.e("App", "Failure", ex);
            }

            return products;
        }
        catch(Exception ex)
        {
            Log.e("App", "yourDataTask", ex);
            return null;
        }
        finally
        {
            if(bufferedReader != null)
            {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    protected void onPostExecute(List<Product> products)
    {
        if(products != null) {
            for (Product product : products) {
                googlemap.addMarker(new MarkerOptions()
                        .position(new LatLng(product.lat, product.lon))
                        .title(product.name)
                        .icon(BitmapDescriptorFactory.fromBitmap(product.icon))
                        );
            }
        }
    }
}

where Product class is: Product类别为:

protected class Product {
    public String name;
    public double lat;
    public double lon;
    public Bitmap icon;
}

getBitmapFromURL() is: getBitmapFromURL()是:

public static Bitmap getBitmapFromURL(String src) {
try {
    URL url = new URL(src);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoInput(true);
    connection.connect();
    InputStream input = connection.getInputStream();
    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
    bmOptions.inSampleSize = 1;
    bmOptions.inJustDecodeBounds = false;
    Bitmap myBitmap = BitmapFactory.decodeStream(input, null, bmOptions);
    return myBitmap;
} catch (IOException e) {
    return null;
}

} }

and You can call it that way (of course after You got reference googlemap to GoogleMap object): 并且您可以用这种方式调用它(当然,在您将googlemap引用到GoogleMap对象之后):

CreateProductListTask responseDownloadTask = new CreateProductListTask("https://www.towncitycards.com/webservice_action.php?action=all_products");
responseDownloadTask.execute();

Finally (after 20-30 sec because of server response delay for non existing icons) You got something like that: 最后(由于不存在的图标服务器响应延迟,在20-30秒后),您得到的是这样的内容:

添加标记结果

And maybe You need to scale icons like in this answer of goodm 也许你需要在规模类似的图标这个答案的goodm

Of course, this is just example and You need Service instead of AsyncTask to download data and images from URL (see Virgil Dobjanschi about patterns ). 当然,这只是示例,您需要Service而不是AsyncTask来从URL下载数据和图像( 有关模式,请参见Virgil Dobjanschi )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM