android google maps api v2显示从url解析xml的标记

时间:2014-04-15 05:28:16

标签: java android xml google-maps google-maps-api-2

我尝试从像lat和longt的xml中获取标记信息并添加到谷歌地图。 这是我的代码 - MainActivity.java

 package com.example.testmap;

import android.app.Activity;
import android.os.Bundle;
import android.location.*;
import android.widget.Toast;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;


 import com.google.android.gms.maps.CameraUpdate;
 import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
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;

public class MainActivity extends Activity {

// Google Map
private GoogleMap googleMap;
LatLng myPosition;

// All static variables
static final String URL = "http://www.urbanbees.co.uk/maps/phpsqlajax_genxml3.php";
// XML node keys
static final String KEY_MARKER = "marker"; // parent node
static final String KEY_NAME = "name";
static final String KEY_ADDRESS = "address";
static final String KEY_LAT = "lat";
static final String KEY_LNG = "lng";
static final String KEY_TYPE = "type";


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    try {
        // Loading map
        initilizeMap();

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

}

/**
 * function to load map. If map is not created it will create it for you
 * */
private void initilizeMap() {
    if (googleMap == null) {
        googleMap = ((MapFragment) getFragmentManager().findFragmentById(
                R.id.map)).getMap();
        googleMap.setMyLocationEnabled(true); // false to disable

        LocationManager locationManager =  (LocationManager) getSystemService(LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        String provider = locationManager.getBestProvider(criteria, true);
        Location location = locationManager.getLastKnownLocation(provider);

                if(location!=null){
        double latitude = location.getLatitude();
        double longitude = location.getLongitude();
        myPosition = new LatLng(latitude, longitude);

        CameraUpdate center= CameraUpdateFactory.newLatLng(new LatLng(latitude,                                                                    longitude));
                             CameraUpdate zoom=CameraUpdateFactory.zoomTo(15);

                    googleMap.moveCamera(center);
                    googleMap.animateCamera(zoom);
                }


                //ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
               // ArrayList<Marker> markers = new ArrayList<Marker>();

                XMLParse parser = new XMLParse();
                String xml = parser.getXmlFromUrl(URL); // getting XML
                Document doc = parser.getDomElement(xml); // getting DOM element

                NodeList nl = doc.getElementsByTagName(KEY_MARKER);
                // looping through all item nodes <item>
                for (int i = 0; i < nl.getLength(); i++) {
                    // creating new HashMap
                    //HashMap<String, String> map = new HashMap<String, String>();
                    Element e = (Element) nl.item(i);
                    // adding each child node to HashMap key => value
                    //map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
                   // map.put(KEY_ADDRESS, parser.getValue(e, KEY_ADDRESS));
                    //map.put(KEY_LAT, parser.getValue(e, KEY_LAT));
                   // map.put(KEY_LNG, parser.getValue(e, KEY_LNG));

                    // adding HashList to ArrayList
                   // menuItems.add(map);

                    double lati=Double.parseDouble(parser.getValue(e, KEY_LAT));
                    double longLat=Double.parseDouble(parser.getValue(e, KEY_LNG));
                    googleMap.addMarker(new MarkerOptions().position(new LatLng(lati,longLat)).title( parser.getValue(e, KEY_NAME)).snippet(parser.getValue(e, KEY_ADDRESS)));


                }                  







        // check if map is created successfully or not
        if (googleMap == null) {
            Toast.makeText(getApplicationContext(),
                    "Sorry! unable to create maps", Toast.LENGTH_SHORT)
                    .show();
        }
    }
}






@Override
protected void onResume() {
    super.onResume();
    initilizeMap();
}

}

这是XMLParse.java

 package com.example.testmap;

 import java.io.IOException;
 import java.io.StringReader;
 import java.io.UnsupportedEncodingException;

 import javax.xml.parsers.DocumentBuilder;
 import javax.xml.parsers.DocumentBuilderFactory;
 import javax.xml.parsers.ParserConfigurationException;

 import org.apache.http.HttpEntity;
 import org.apache.http.HttpResponse;
 import org.apache.http.client.ClientProtocolException;
 import org.apache.http.client.methods.HttpPost;
 import org.apache.http.impl.client.DefaultHttpClient;
 import org.apache.http.util.EntityUtils;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
 import org.w3c.dom.NodeList;
 import org.xml.sax.InputSource;
 import org.xml.sax.SAXException;

 import android.util.Log;

 public class XMLParse {

// constructor
public XMLParse() {

}

/**
 * Getting XML from URL making HTTP request
 * @param url string
 * */
public String getXmlFromUrl(String url) {
    String xml = null;

    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        xml = EntityUtils.toString(httpEntity);

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    // return XML
    return xml;
}

/**
 * Getting XML DOM element
 * @param XML string
 * */
public Document getDomElement(String xml){
    Document doc = null;
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    try {

        DocumentBuilder db = dbf.newDocumentBuilder();

        InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(xml));
            doc = db.parse(is); 

        } catch (ParserConfigurationException e) {
            Log.e("Error: ", e.getMessage());
            return null;
        } catch (SAXException e) {
            Log.e("Error: ", e.getMessage());
            return null;
        } catch (IOException e) {
            Log.e("Error: ", e.getMessage());
            return null;
        }

        return doc;
}

/** Getting node value
  * @param elem element
  */
 public final String getElementValue( Node elem ) {
     Node child;
     if( elem != null){
         if (elem.hasChildNodes()){
             for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
                 if( child.getNodeType() == Node.TEXT_NODE  ){
                     return child.getNodeValue();
                 }
             }
         }
     }
     return "";
 }

 /**
  * Getting node value
  * @param Element node
  * @param key string
  * */
 public String getValue(Element item, String str) {     
        NodeList n = item.getElementsByTagName(str);        
        return this.getElementValue(n.item(0));
    }
 }

没有错误。地图有效,但标记没有显示在地图中。

0 个答案:

没有答案