我在 PHP 页面中使用 Google Maps Javascript API,并希望将用户通过 PHP 接收到的值(基本上是用户输入的地址)用于 map JS 代码。我的代码大致设置如下:
<?php $myVar = "new york"; ?>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDwKLaKFqCqNs61pylmB8Yqj6I0v1LhE-A">
</script>
<script type="text/javascript">
var latitude, longitude;
var geocoder = new google.maps.Geocoder();
var location = <?php echo json_encode($myVar); ?>;
geocoder.geocode({ "address": location}, function(results, status){
latitude = results[0].geometry.location.lat();
longitude = results[0].geometry.location.lng();
});
function initialize() {
var mapOptions = {
center: { lat: latitude, lng: longitude},
zoom: 8
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
但是,每次我尝试运行它时,字符串“new york”都会添加到我的 URL 中,如下所示:
http://localhost:8888/quill/shows/the-merchant-of-venice/new%20york
为什么会发生这种情况,我该如何预防?
最佳答案
由于您的代码位于顶层,您的变量location
实际上是window.location
,用于设置页面的URL。
将所有 Javascript 代码放在 IIFE 中给它自己的变量范围:
(function() {
var latitude, longitude;
var geocoder = new google.maps.Geocoder();
var location = <?php echo json_encode($myVar); ?>;
geocoder.geocode({ "address": location}, function(results, status){
latitude = results[0].geometry.location.lat();
longitude = results[0].geometry.location.lng();
});
function initialize() {
var mapOptions = {
center: { lat: latitude, lng: longitude},
zoom: 8
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
})();
关于javascript - <script> 代码中使用的 PHP 变量被添加到 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29977097/