Where The Streets Have No Name

google map에서 주소를 검색해서 선택시 해당위치에 marker표시 본문

Developement/GIS

google map에서 주소를 검색해서 선택시 해당위치에 marker표시

highheat 2011. 8. 16. 16:29
<!DOCTYPE html> 
<html> 
<head> 
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/> 
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
<title>Google Maps JavaScript API v3 Example: Geocoding Simple</title> 
<link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" /> 
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script> 
<script type="text/javascript"> 
var geocoder;
var map;
var marker;

function initialize(){
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions = {
        zoom: 8,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}

function codeAddress(){
    var address = document.getElementById("address").value;
	var r = document.getElementById("r");
	
	r.innerHTML = '';
	
    geocoder.geocode({
        'address': address
    }, function(results, status){
        if (status == google.maps.GeocoderStatus.OK) {
            map.setCenter(results[0].geometry.location);
			addMark(results[0].geometry.location.lat(), results[0].geometry.location.lng());
						
			for(var i in  results){
				//r.innerHTML += results[i].formatted_address+',';
				var li = document.createElement('li');
				var a = document.createElement('a');
				a.href = "javascript:addMark(" + marker.position.lat() + ", " + marker.position.lng() + ");";
				a.innerHTML = results[i].formatted_address;
 
				li.appendChild(a);
				r.appendChild(li);
			}			
        } else {
			r.innerHTML = "검색 결과가 없습니다."+status;            
        }
    });
}

function addMark(lat, lng){
	if(typeof marker!='undefined'){
		marker.setMap(null);
	}
	
    marker = new google.maps.Marker({
    	map: map,
        position: new google.maps.LatLng(lat, lng)
    });
}

</script> 
</head> 
<body onload="initialize()"> 
<div> 
	<input id="address" type="textbox" value="Sydney, NSW"> 
    <input type="button" value="Geocode" onclick="codeAddress()"> 
</div> 
<div id="r"></div>  
<div id="map_canvas" style="height:90%;top:30px"></div> 
</body> 
</html>