Problems with Node.js and naver map api

Issue

This Content is from Stack Overflow. Question asked by Joonhwan

hello i’ve made pharmacy searching based on where i am with node.js and naver map api so far it shows like this
enter image description here

and i wanna add this one to the code
enter image description here

it tells me to add overlay, i’ve tried many times to revise my code, but didnt work at all
can anyone possibly help me to figure out where should be fixed?

this is my index.html down below

        <script>
            $(document).ready(async function(){
                let XY = await getLocation();
                //alert("위도" + XY.lat);
                //alert("경도" + XY.lng);

                // reverseGeocode는 비동기형이라 await 추가
                await naver.maps.Service.reverseGeocode({
                    location: new naver.maps.LatLng(XY.lat, XY.lng)
                },function(status, response){
                    let result = response.result;
                    let items = result.items;
                    //console.log(items[0].addrdetail.sido);
                    //console.log(items[0].addrdetail.sigugun);
                    let sido_arr = items[0].addrdetail.sido.split(" ");
                    let gubun_arr = items[0].addrdetail.sigugun.split(" ");

                    let sido = "";
                    let gubun = "";
                    if(sido_arr.length ==1) {
                        sido = sido_arr[0];
                        gugun = gubun_arr[0]
                    }


                    else if(sido_arr.length > 1) {
                        sido = sido_arr[0];
                        gugun = sido_arr[1]
                    }
                    console.log(sido);
                    console.log(gugun);


                    $.ajax({
                        url: "/pharmach_list",
                        type: "GET",   // GET을 통해 밑에 주석처리한 api url 부분 ?뒤부터 눈에 보이게끔 값들을 하나하나 입력해줌
                        cache: false,  //cache는 쓰지 않을거라 false
                        dataType: "json",    //dataType은 json으로 받겠다
                        data: {"Q0": sido, "Q1": gugun, "QT": "", "QN": "", "ORD": "", "pageNo": "1", "numOfRows": "1000"},   
                        success: function(data) {
                            console.log(data);
    
    
                            //지도를 삽입할 HTML 요소 또는 HTML 요소의 id를 지정합니다.
                            var mapDiv = document.getElementById('map'); // 'map'으로 선언해도 동일
    
                            //옵션 없이 지도 객체를 생성하면 서울 시청을 중심으로 하는 16 레벨의 지도가 생성됩니다.
                            var mapOptions = {
                                center: new naver.maps.LatLng(XY.lat, XY.lng),
                                zoom: 14
                            }
                            var map = new naver.maps.Map(mapDiv, mapOptions);
                            
                            data.items.item.forEach(function(it, index){
                                let dutyName = it.dutyName;
                                let dutyAddr = it.dutyAddr;
                                let dutyTel1 = it.dutyTel1;

                                let dutyTime = "";
                                if(it.dutyTime1s && it.dutyTime1c) {
                                    dutyTime += "월요일: " + it.dutyTime1s + " ~ " + it.dutyTime1c + "<br>";
                                }
                                let pharmacy_location = new naver.maps.LatLng(it.wgs84Lat, it.wgs84Lon)

                                    let marker = new naver.maps.Marker({
                                        map: map,
                                        position: pharmacy_location
                                    });
                                
                                    var contentString = [
                                            '<div class="iw_inner">',
                                            '   <h3>'+dutyName+'</h3>',
                                            '   <p>'+dutyAddr+'<br />', 
                                            '       '+dutyTel1+'<br />',
                                            '       '+dutyTime,
                                            '   </p>',
                                            '</div>'
                                        ].join('');
                                    
                                    var infowindow = new naver.maps.InfoWindow({
                                        content: contentString,
                                        maxWidth: 440,
                                        backgroundColor: "#eee",
                                        borderColor: "#2db400",
                                        borderWidth: 5,
                                        anchorSize: new naver.maps.Size(30, 30),
                                        anchorSkew: true,
                                        anchorColor: "#eee",
                                        pixelOffset: new naver.maps.Point(20, -20)
                                    });
                                    
                                    naver.maps.Event.addListener(marker, "click", function(e) {
                                        if (infowindow.getMap()) {
                                            infowindow.close();
                                        } else {
                                            infowindow.open(map, marker);
                                        }                                        
                                    });
  
                                    });
    
                        },
                        error: function(request, status, error) {                            
                        }
                    });
                });
            });

            // geolocation은 gps와 관련된 객체, 이 객체가 존재하면 getLocation 실행함
            // getCurrentPosition 사용시 현재 위치를 알 수 있다, position 이라는 객체를 통해 현 위치 파악
            async function getLocation() {
                let XY = new Object();
                if(navigator.geolocation) {
                    
                    let promise = new Promise((resolve, rejected) => {
                        navigator.geolocation.getCurrentPosition((position) => {
                            resolve(position);
                        });
                    });


                    let position = await promise;
                


                    //위도 position.coords.latitude 
                    //경도 position.coords.longitude 
                    XY.lat = position.coords.latitude
                    XY.lng = position.coords.longitude
  
                }
                return XY;     
            }
        </script>    
</html>

and this is the overlaycode from naver api, that i’ve got

var CustomOverlay = function(options) {
    this._element = $('<div style="position:absolute;left:0;top:0;width:124px;background-color:#F2F0EA;text-align:center;border:2px solid #6C483B;">' +
                        '<img src="./img/example/brown.png" style="width: 120px; height:130px">' +
                        '<span style="font-weight: bold;"> Brown </span>' +
                        '</div>')

    this.setPosition(options.position);
    this.setMap(options.map || null);
};

CustomOverlay.prototype = new naver.maps.OverlayView();
CustomOverlay.prototype.constructor = CustomOverlay;

CustomOverlay.prototype.setPosition = function(position) {
    this._position = position;
    this.draw();
};

CustomOverlay.prototype.getPosition = function() {
    return this._position;
};

CustomOverlay.prototype.onAdd = function() {
    var overlayLayer = this.getPanes().overlayLayer;

    this._element.appendTo(overlayLayer);
};

CustomOverlay.prototype.draw = function() {
    if (!this.getMap()) {
        return;
    }

    var projection = this.getProjection(),
        position = this.getPosition(),
        pixelPosition = projection.fromCoordToOffset(position);

    this._element.css('left', pixelPosition.x);
    this._element.css('top', pixelPosition.y);
};

CustomOverlay.prototype.onRemove = function() {
    var overlayLayer = this.getPanes().overlayLayer;

    this._element.remove();
    this._element.off();
};

var position = new naver.maps.LatLng(37.3849483, 127.1229117);
var map = new naver.maps.Map("map", {
    center: position,
    zoom: 19
});
var overlay = new CustomOverlay({
    map: map,
    position: position
});

naver.maps.Event.addListener(map, 'click', function(e) { //클릭한 위치에 오버레이를 추가합니다.
    var overlay = new CustomOverlay({
        position: e.coord
    });

    overlay.setMap(map);
});



Solution

This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?