実現したいこと
Maps JavaScript API
GeoCoding API
を利用したサービスを実装しています。
HTML上にボタンを設置し、ボタンを押下するとPHPで諸々の処理が行われ、GeoCoding APIに渡すアドレス情報が生成されます。この情報をJavaScript関数の引数に渡してその関数を実行することで、場所検索を行いたいと考えています。
発生している問題
下記ソースコードのようにJavaScript関数を呼び出そうとしました。
生成されたソースは関数を呼んでいましたが、
Uncaught ReferenceError: google is not defined
とのエラーが出力されていました。
この「google」がどこで定義されているのかが不明なため、どのように対処すればよいか分かりません。
該当のソースコード
Javascript
1<script> 2 3 function initMap() { 4 5 //とりあえずオーストラリアを表示 6 var uluru = {lat: -25.363, lng: 131.044}; 7 var map = new google.maps.Map(document.getElementById('map'), { 8 zoom: 12, 9 center: uluru 10 }); 11 12 //geocode--------------------------------------▼ 13 14 var address ="東京都立中央図書館";//初期表示する場所 15 var geocoder = new google.maps.Geocoder(); 16 geocodeAddress(geocoder, map, address);//初回起動時は正しく呼び出しできている 17 } 18 19 //PHPからこの関数を呼び出したい 20 function geocodeAddress(geocoder, resultsMap, address) 21 { 22 geocoder.geocode({'address': address}, function(results, status) { 23 if (status === google.maps.GeocoderStatus.OK) { 24 resultsMap.setCenter(results[0].geometry.location); 25 var marker = new google.maps.Marker({ 26 map: resultsMap, 27 position: results[0].geometry.location 28 }); 29 } else { 30 alert('Geocode was not successful for the following reason: ' + status); 31 } 32 }); 33 } 34 35 </script>
php
1<?php 2 3 if ($_SERVER["REQUEST_METHOD"] === "POST") { 4 5 // APIキー 6 $api_key = "xxxxxxxxxxxxxxxxxxxx" ; 7 8 // ---------------省略:取得したデータを$textにセット------------- 9 10 echo '<script type = "text/javascript">'; 11 echo 'var geocoder = new google.maps.Geocoder();';//★ここでエラー 12 echo 'geocodeAddress(geocoder, map, "'.$text.'");'; 13 echo '</script>';
JavaScript、PHP共に扱いはじめて間もないため、初歩的な問題の可能性もあるかと思います。些細なことでもお気づきの点があればご教授頂ければ幸いです。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/05/21 23:00