2011-10-21 4 views
1

Google지도 api javascript v3의 간단한 hello world 버전이 있으며 정적 지오 코드로 작동합니다. 내 데이터는 일반적인 주소 (즉, "30 rockefeller center, New York, NY")입니다.Google지도 API v3 - 간단하지만 php/mysql 주소의 지오 코드를 추가하십시오.

이 데이터는 mysql 데이터베이스의 php에서 호출됩니다. 나는이 글의 목적이 같은 ...이있는 페이지의 주소를 얻을 수있는, 말하자면이 모든 정보 것 : 주소, 도시, 주, 우편 번호 그래서

<?php echo $row_query_details['address'];?> 

을, 나는 지오 코딩 할 필요가 지도에 대한이 정보. 나는 mysql과 PHP에 매우 익숙하지만 자바 스크립트에서는 그렇지 않다. 나는 이틀 동안 시행 착오와 연구를 해왔다.

나는 실제 샘플이나 예제를 찾아 보았는데,이 비교적 단순한 문제가 여러 차례에 걸쳐 질문을 받고 대답해야했음을 느낀다. 그러나 나는 그것을 이해할 수 없다!

미리 감사드립니다.

  <!DOCTYPE html> 
      <html> 
      <head> 
      <meta name="viewport" content="initial-scale=1.0, user-scalable=no" /> 
      <style type="text/css"> 
       html { height: 100% } 
       body { height: 100%; margin: 0; padding: 0 } 
       #map_canvas { height: 100% } 
      </style> 
      <script type="text/javascript" 
       src="http://maps.googleapis.com/maps/api/js?sensor=false"> 
      </script> 
      <script type="text/javascript"> 
       function initialize() { 
       var latlng = new google.maps.LatLng(-34.397, 150.644); 
       var myOptions = { 
        zoom: 8, 
        center: latlng, 
        mapTypeId: google.maps.MapTypeId.ROADMAP 
       }; 
       var map = new google.maps.Map(document.getElementById("map_canvas"), 
        myOptions); 
      var marker = new google.maps.Marker({ 
        position: latlng, 
        title:"Hello World!" 
       }); 

       // To add the marker to the map, call setMap(); 
       marker.setMap(map); 
       } 

      </script> 
      </head> 
      <body onload="initialize()"> 
       <div id="map_canvas" style="width:500px; height:500px"></div> 
      </body> 
      </html> 

답변

0

그래서 여기에 내 자신의 질문에 대답 할 것입니다. 첫 번째 대답은 utlize 수 없습니다. 대답이 불완전하거나 잘 모르겠다. 나는 MySQL의 DB에서 끌어 내 주소 구성 요소를 가지고 내가 이렇게 그들에게 변수를 할당

첫째 :

다음
$county = $row_qry['county']; 
$address = $row_qry['address']; 
$city = $row_qry['city']; 
$state = $row_qry['state']; 

, 내 구글 V3 물건이 보이는 관계없이, 여기에 같은 코드가 어떻게 표시되는지를 보여줍니다 :

  <script type="text/javascript" src="//maps.googleapis.com/maps/api/js?sensor=false"></script> 
      <script type="text/javascript"> 
       var geocoder; 
       var map; 
       function initialize() { 
       geocoder = new google.maps.Geocoder(); 
       var latlng = new google.maps.LatLng(34.052234,-118.243685); 
       var address = '<?php echo $address.', '.$city.', '.$state; ?>'; 

       var myOptions = { 
        zoom: 14, 
        center: latlng, 
        mapTypeId: google.maps.MapTypeId.ROADMAP 
       } 
       map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); 
       geocoder.geocode({ 'address': address}, function(results, status) { 
        if (status == google.maps.GeocoderStatus.OK) { 
        map.setCenter(results[0].geometry.location); 
        var marker = new google.maps.Marker({ 
         map: map, 
         position: results[0].geometry.location 
        }); 
        } else { 
        alert("Geocode was not successful for the following reason: " + status); 
        } 
       }); 
       } 


      </script> 

그리고 그 종류의 대답은 내 질문입니다. (a) 마커를 클릭 할 수 있고 대화식으로 만드는 방법, (b) 올바른 주소를 표시하기 전에지도가 먼저 정의 된 지오 코드 (34.05, -118.24)를 깜박 거는 등 해결해야 할 몇 가지 문제가 있습니다. .

적어도 두 가지 문제는 해결해야하지만 적어도 지오 코딩이 성공적으로 작동합니다. 희망이 다른 사람을 도와줍니다.

감사합니다.

0

당신은 기능에 초기화()를 PHP 변수를 전달하여 자바 스크립트로 PHP 변수를 사용할 수 있습니다 : 여기

내가 함께 일하고 있어요 코드입니다.

body 태그는 아래와 같이 표시됩니다. 예를 들어

:

<body onload="initialize('<?php echo $row_query_details['address'];?>')">

그럼 당신은 당신의 자바 스크립트 코드에서이 특정 변수를 사용하여 자바 스크립트 함수는 다음과 같이 표시됩니다

<script type="text/javascript"> 
       function initialize(address) { 

       var G_address = address; 

       var latlng = new google.maps.LatLng(-34.397, 150.644); 
       var myOptions = { 
        zoom: 8, 
        center: latlng, 
        mapTypeId: google.maps.MapTypeId.ROADMAP 
       }; 
       var map = new google.maps.Map(document.getElementById("map_canvas"), 
        myOptions); 
      var marker = new google.maps.Marker({ 
        position: latlng, 
        title:"Hello World!" 
       }); 

       // To add the marker to the map, call setMap(); 
       marker.setMap(map); 
       } 

      </script> 

지금이 G_address 자바 스크립트를 사용할 수 있습니다 변수를 동적으로 G-MAP 코드에서 찾을 수 있습니다 ..

이것은 당신에게 유용 할 것입니다 ..

2

안녕하세요. 행복한 기념일 (질문 및 학습 자료 관련). 나는 웹 개발자이며 고맙습니다. 이 튜토리얼은 현재 사이트를 컨설팅하고 백엔드 코드에 최소한의 액세스 권한을 부여하므로 제출 (위도/경도를 db에 저장된 주소에서 가져와야 함)을 통해 지오 코딩 할 수있는 방법이 없습니다.

1) 일부 콘텐츠 제공 :

마커의 상호 작용에 대한 귀하의 질문에 대답하기 위해,이 몇 가지 간단한 조치를 취하고 있습니다.

마커 선언의 아래에
var contentString = 
    'line 1'+ 
    'line 2'; 

2) (var에 마커 = 새로운 google.maps.Marker ({), 당신은 정보창을 선언하고 이벤트를 추가해야합니다 (VAR 지오 코더)이 지오 코더를 선언하기 전에 완료 청취자 :

var infowindow = new google.maps.InfoWindow({ 
content: contentString 
}); 
google.maps.event.addListener(marker, 'click', function() { 
infowindow.open(map,marker); 
}); 

편집 :

나는 성공적 방식에 확대하여 MySQL 데이터베이스에서 배열 정보를 당긴 내 방법은 여기

:.

아래

1) 기본 PHP : 아래

<script type="text/javascript" 
    src="http://maps.googleapis.com/maps/api/js?key=yourkey&sensor=false"> 
</script> 

3) 지오 코딩 설정 :

<script type="text/javascript"> 
var geocoder; 
var map; 
function initialize() { 
var latlng = new google.maps.LatLng(yourlat, yourlong); //This is to center the map 
var myOptions = { 
zoom: 8, 
center: latlng, 
mapTypeId: google.maps.MapTypeId.ROADMAP 
       } 
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); 
<?php //Starts while loop so all addresses for the given information will be populated. 
while($row = mysql_fetch_array($result)) //instantiates array 
{ ?>    
geocoder = new google.maps.Geocoder(); 
var address = '<?php echo $row['address'].', '.$row['city'].', '.$row['state'].', '.$row['zip'].', '.$row['country']; ?>'; 
geocoder.geocode({ 'address': address}, function(results, status) { 
if (status == google.maps.GeocoderStatus.OK) { 
//marker generation is done though adding the primary ID to the "marker" variable, so if address "1" has the primary ID of "1", your marker would read "marker1" 
var marker<?php print $row['primaryID']; ?> = new google.maps.Marker({ 
map: map, 
position: results[0].geometry.location, 
title: "This can be a php variable or whatever you like. It is displayed on hover." 
        }); 

//var contentString manages what is seen inside of the popup    
var contentString = 
'line 1'+ 
'line 2'; 

var infowindow = new google.maps.InfoWindow({ 
content: contentString 
}); 
google.maps.event.addListener(marker<?php print $row['primaryID']; ?>, 'click', function() { 
infowindow.open(map,marker<?php print $row['primaryID']; ?>); 
        }); 
        } else { 
        alert("Geocode was not successful for the following reason: " + status); 
        } 
       }); 
       <?php 
    $count++; 
} //ends while 
?> 
       } 

/*end javascript*/ 
</script> 

이 게시 대단히 다시 한번 감사드립니다

include (dbinfo.php) 
$result = mysql_query('SELECT * FROM table') 
$count = 0 

2) 구글지도 API 설정 이. 그것은 매우 유용했습니다.