/*初始化地图*/
var map, markersArray = [], geocoder;
function init(){
    var myLatlng = new qq.maps.LatLng(39.916527,116.397128);
    var myOptions = {
        zoom: 16,
        center: myLatlng,
        mapTypeId: qq.maps.MapTypeId.ROADMAP,
        disableDefaultUI: true
    };

    map = new qq.maps.Map(document.getElementById("container"), myOptions);

    qq.maps.event.addListener(
        map, 'click', function(event) {
            var latLng = new qq.maps.LatLng(event.latLng.getLat(), event.latLng.getLng());
            if (geocoder == null) geocoder = getGeocoder();
            geocoder.getAddress(latLng);
        }
    );

    /*地图地址查询*/

    var lat = $("#latitude").val();
    var lng = $("#longitude").val();
    var addressSearch = $("#addressSearch").val();

    if (lat != null && "" != lat && lng != null && "" != lng){
        var latLng = new qq.maps.LatLng(lat, lng);
        if (geocoder == null) geocoder = getGeocoder();
        geocoder.getAddress(latLng);

    }else if (addressSearch != null && "" != addressSearch) {
        if (geocoder == null) geocoder = getGeocoder();
        geocoder.getLocation(addressSearch);
    }

    /*地图地址查询*/
    $("#searchBtn").click(function() {
        if (geocoder == null) geocoder = getGeocoder();
        geocoder.getLocation($("#addressSearch").val());
    });

    /*地图坐标查询*/
    $("#searchCoordBtn").click(function () {
        var vlat = $("#latitude").val();
        var vlng = $("#longitude").val();

        // 根据坐标获取位置
        var vlatLng = new qq.maps.LatLng(vlat, vlng);

        if (geocoder == null) {
            geocoder = getGeocoder();
        }
        // 显示位置
        geocoder.getAddress(vlatLng);

    });

}

function getGeocoder(){
    geocoder = new qq.maps.Geocoder({
        complete : function(result){

            clearOverlays();

            var addComp = result.detail.addressComponents;

            $("#addressSearch").val(result.detail.address);
            $("#city").val(addComp.city);
            $("#latitude").val(result.detail.location.lat);
            $("#longitude").val(result.detail.location.lng);

            //添加标记
            map.setCenter(result.detail.location);
            var marker = new qq.maps.Marker({
                map:map,
                position: result.detail.location,
                draggable: false
            });
            markersArray.push(marker);
        }
    });
    return geocoder;
}

//清除覆盖层
function clearOverlays() {
    if (markersArray) {
        for (i in markersArray) {
            markersArray[i].setMap(null);
        }
    }
}

window.onload = init;
/*初始化地图*/

