본문 바로가기

프로그래밍/JQUERY / JSON

구글(google map) 맵 달기 (jquery, json)

구글 맵 달기 정리.(PHP, JAVASCIRPT, JQUERY, JSON)



위치 정보를 알려줄때 구글 맵을 많이 이용한다..

아래는 소스 위주로 설명을 한다.


우선 구글 맵 api를 전반적인 설명은 아래 사이트 에서 참고 하면 된다.

https://developers.google.com/maps/documentation/javascript/reference?hl=ko




참고로 자바스크립트 api를 이용하였다.


이건 구글맵 튜토리얼이다. 보고 원하는 지도에 대한 소스를 카피해서 홈페이지에 붙이면 된다.

https://developers.google.com/maps/documentation/javascript/tutorial#api_key


사실 해당 홈페이지에서 제공하는 튜토리얼 만한것은 없다. 그러니 열심히 읽어보고 적용하는 수 밖에




기본적으로 자바스크립트 API를 이용하고 jQuery를 이용하였고 데이터는 Json을 이용함.



==== main소스(대부분의 소스는 구글 API에서 가져옴)====


$(document).ready(function(){

    

    $("#msgbox").css("display", "block");

    $("#msg").html("검색중 입니다.").css("color", "black");    --> 데이터를 가져오기전에 조회중이라는 말을 넣어주기 위한것

    

    var map;    

    var avg_center;           

    var info_window = new google.maps.InfoWindow({content: ''});

    var markersArray = [];   

    coordinates = [];

    

    var bounds = new google.maps.LatLngBounds();

    var myLatLng = new google.maps.LatLng(49.246069, -123.013229);  //지도가 로딩이 될때 최초 보여주는 중심지역(중심이 될 지역을 위도, 경도를 구해서 셋팅해준다. 아래 주소를 보면 주소->위도,경도 주소로 바꾸는 많은 페이지들이 있다.)

https://www.google.ca/#hl=en&sclient=psy-ab&q=%EC%9C%84%EB%8F%84+%EA%B2%BD%EB%8F%84+%EA%B5%AC%ED%95%98%EA%B8%B0&oq=%EC%9C%84%EB%8F%84+%EA%B2%BD%EB%8F%84+%EA%B5%AC%ED%95%98%EA%B8%B0&gs_l=hp.3..0j0i8i30.311.3526.0.3854.26.18.2.2.2.5.325.2240.8j9j0j1.18.0.les%3B..0.0...1c.1j4.5.psy-ab.3s1ocMfLo5o&pbx=1&bav=on.2,or.r_gc.r_pw.r_qf.&bvm=bv.43148975,d.aWM&fp=40adf5b9903408a9&biw=1600&bih=775

    

      

    var myOptions = {

        zoom : 9,                  //최초 줌 설정.

        center : myLatLng,    //최초 중심이 될 지역

        mapTypeId : google.maps.MapTypeId.ROADMAP    //구글 맵 타입 (ROADMAP)

    };


    map = new google.maps.Map(document.getElementById("map1"), myOptions);  //구글맵을 뿌려줄 영역에다가 기본값을 넣어서 (Html body 아이디가(id) map1이라는 영역을 지정했음.

    

    //json을 이용해서 데이터 가져오기. 검색 창도 마련해서 검색조건이 있으면 같이 넘겨줌.

    //형식 $.getJSON("데이터를 가져올 주소", "function(json){  


    $.getJSON("address_data.php?search_title=<?=$search_title?>&search_location_sub=<?=$search_location_sub?>&search_type_sub=<?=$type?>", function(json) {    


        //넘어온 데이터의 갯수를 찍는다.        

        if (json.markers.length > 0) {                 

                

            //json객체로 넘어온 데이터를 제이쿼리 each문을 통해서 찍는다.

            $.each(json.markers,function() {      


                //각각의 위도 경도 값을 구글 맵에다 넣어서 평균 센터값을 만든다.

                avg_center = new google.maps.LatLng(this["stLat"], this["stLng"]);    

                coordinates.push(avg_center);     //평균 센터값 push

                

    //데이터베이스에서 구한 값을 가지고 마커를 찍는다.(아래 add_marker 함수 호출)

                add_marker(this["stId"], this["stLat"], this["stLng"], this["stFullAddr"], this["stTitle"], this["stPhone"], this["stFax"], this["stNotice"], this["stWebsite"], this["imageFile1"], this["stTypeSubId"]);

            

            });

            

            

            bounds = new google.maps.LatLngBounds();


            for(var k=0;k<json.markers.length;k++){

                bounds.extend(coordinates[k]);

            }

            

            //마커를 다 찍으면 결과를 display한다.

            $("#msgbox").css("display", "block");

            $("#msg").html("총 " + json.markers.length + "의 업체가 조회되었습니다.").css("color", "blue");

            

        }else{

            

            $("#msgbox").css("display", "block");

            $("#msg").html("검색 결과가 없습니다.").css("color", "red");

            

        }

        

    });

    


    function add_marker(stId, lat, lng, addr, name, phone, fax, notice, website, img, stTypeSubId) {

        

        //위도 경도로 위치 설정

        var loc = new google.maps.LatLng(lat, lng);

        

        //아래 이하는 마커를 클릭했을때 정보창 나오게 하기 위해서


        //fax번호

        if(fax == null || fax == ""){

            fax = "N / A";

        }

        

        //홈페이지 주소

        if(website == null || website == ""){

            website = "N / A";

        }


        //구글에서 제공하는 기본 마커를 바꾸고 싶으면 아래변수를 지정해서 이미지 경로를 적어 주면 됨.

        //예를 들어 공공기관 : a이미지, 병원 : b이미지 등등..               

        var icon_img;

       

        //마커 정보를 묶는다.

        var opts = {

            map: map, 

            position: loc, 

            animation: google.maps.Animation.DROP,   //하늘에서 마커가 지도로 찍히는 애니메이션..표현이 참 ㅋ

            clickable: true,

            icon : icon_img

                  

        };

        

        var marker = new google.maps.Marker(opts);

        

        //위의 정보들에 대해서 인포메이션 창을 만드는 단계

        var bsInfo = "<table height='70'>";

        bsInfo = bsInfo + "<tr>";

        bsInfo = bsInfo + "<td width='67' valign='top'>";

        

    

        bsInfo = bsInfo + "<a href='http://www.vanchosun.com/stores/main/frame.php?main=stores&stId=" +stId + "' target='_blank'><img src='http://www.vanchosun.com/stores/images_site/image-temp.gif' width='67px' height='59px' style='border: #dddddd 1px solid'></a>";

            

    

        marker.html = bsInfo;         

                

        //마커를 찍는다.

        markersArray.push(marker);

        


        //마커를 클릭했을시

        google.maps.event.addListener(marker, 'click', function() {

                             

            info_window.setContent(this.html);  //인포메이션 창 띄운다.

            info_window.open(map, marker);

            map.setZoom(12);                         //줌은 12배

            map.setCenter(loc);                      //클릭 마커가 화면 중심

            marker.setAnimation(google.maps.Animation.BOUNCE);  //애니메이션 바운스(필요없으면 빼도됨)

        });

        

        return marker;

    }

});




====데이터 찍기 Json타입(main에서 $.getJSON이 호출하는 페이지 ====


    //조회 파라미터 받는다.

    $search_title = $_GET["search_title"];

    $search_location_sub = $_GET["search_location_sub"];

    $search_type_sub = $_GET["search_type_sub"];

    

    //조회조건과 함께 쿼리문을 만든다.

    //select * from AAAA

                                            

    //json데이터 이름 정하고.  

    $markers = array("stores");

    

    

    if(조회값이 있으면 > 0){  //조회값이 있으면 카운터 만큼 돌린다.


        while($row = mysql_fetch_array($BDP_sel_pre, MYSQL_ASSOC)){

            

            $BLC = new BoardLocationcategory();        

            

            $gm_city = $BLC->ReadLocationCategorySubName($row['stLocationSubId']);

            $gm_province = $BLC->ReadLocationCategoryName($row['stLocationId']);

            

            $sAddress = $row["stAddress"]." ".$gm_city." ".$gm_province." ".$row['stPostal'];

            

            array_push($markers, array('stId' => $row['stId']

                                                    , 'gm_province' => $gm_province

                                                    , 'gm_city' => $gm_city

                                                    , 'stTypeId' => $row['stTypeId']

                                                    , 'stTypeSubId' => $row['stTypeSubId']

                                                    , 'stTitle' => $row['stTitle']

                                                    , 'stName' => $row['stName']

                                                    , 'stEmail' => $row['stEmail']

                                                    , 'stCity' => $row['stCity']

                                                    , 'stAddress' => $row['stAddress']

                                                    , 'stPostal' => $row['stPostal']

                                                    , 'stPhone' => $row['stPhone']

                                                    , 'stFax' => $row['stFax']                                                                                              

                                                    , 'stWebsite' => $row['stWebsite']

                                                    , 'stNotice' => $row['stNotice']

                                                    , 'imageFile1' => $row['imageFile1']

                                                    , 'stFullAddr' => $sAddress

                                                    , 'stLat' => $row['stLat']

                                                    , 'stLng' => $row['stLng']

                                                   ));

        }

        

        echo json_encode(array("markers" => $markers));    

        exit;

        

    }else{

       //echo "데이터 없음";

    }



<<<참고 사항 

 - 서버단에서 주소를 가지고 경도 위도로 변환해서 하면 구글에서 에러를 발생 시킨다. 서버에 부하가 된다고 하래나 뭐래나 아무튼..여기서 말고 주소를 입력할때 그때 건건히 위도, 경도를 구해서 넣고 지도에 뿌릴때는 데이터베이스 데이터를 가지고 그냥 뿌리는것이 좋을것이다.