javascript - PHP 和 Javascript 问题 - SyntaxError:不能两次声明 const 变量:'map'
问题描述
我正在尝试使用 JSON 文件中的 long/lat 列表填充谷歌地图并遇到此问题,我们将不胜感激!
[错误] SyntaxError:不能两次声明 const 变量:'map'。
[错误] 未处理的 Promise Rejection: InvalidValueError: initMap is not a function
<!-- Async script executes immediately and must be after any DOM elements used in callback. -->
<script
src="https://maps.googleapis.com/maps/api/js?key=MYAPIKEY&callback=initMap&libraries=&v=weekly"
async
></script>
<script>
// Initialize and add the map
function initMap() {
// The location of Uluru
const uluru = { lat: -25.344, lng: 131.036 };
// The map, centered at Uluru
const map = new google.maps.Map(document.getElementById("map"), {
zoom: 5,
center: uluru,
});
// The marker, positioned at Uluru
<?php
$data = json_decode($eaterJSON,true);
$data = array_values( array_unique( $data, SORT_REGULAR ) );
$clean = json_encode($data);
// print_r($clean);
foreach($data as $key => $value) {
?>
const map = new google.maps.Marker({
position: {lat: <?php echo $value['lat'] ?>, lng: <?php echo $value['lon'] ?>},
map: map,
});
<?php
}
?>
}
</script>
解决方案
您需要将第二个地图const 重命名为marker:
从:const map = new google.maps.Marker({
到:const marker = new google.maps.Marker({
更新: 哦,等等!您使用 PHP 循环生成 JS 代码(标记),这会导致多个相同的变量名!请详细了解(多个)标记创建!
在这种情况下,您无需为变量分配标记,只需在循环中创建标记:
<!-- Async script executes immediately and must be after any DOM elements used in callback. -->
<script
src="https://maps.googleapis.com/maps/api/js?key=MYAPIKEY&callback=initMap&libraries=&v=weekly"
async
></script>
<script>
// Initialize and add the map
function initMap() {
// The location of Uluru
const uluru = { lat: -25.344, lng: 131.036 };
// The map, centered at Uluru
const map = new google.maps.Map(document.getElementById("map"), {
zoom: 5,
center: uluru,
});
// The marker, positioned at Uluru
<?php
$data = json_decode($eaterJSON,true);
$data = array_values( array_unique( $data, SORT_REGULAR ) );
$clean = json_encode($data);
// print_r($clean);
foreach($data as $key => $value) {
?>
new google.maps.Marker({
position: {lat: <?php echo $value['lat'] ?>, lng: <?php echo $value['lon'] ?>},
map: map,
});
<?php
}
?>
}
</script>
推荐阅读
- cmake - 如何使用 CMake 在特定目录中收集目标文件 (.o)?
- php - Symfony 无法加载 TextType 类
- c# - NEST 返回 null 而不是字段
- java - 如何在 docker push 命令期间修复 EOF?
- mongodb - 覆盖与特定 ObjectId 关联的数据?
- javascript - 产品密钥 javascript 正则表达式失控
- php - Symfony 控制器中的表单
- php - 网页滚动超越了 body 和 html 标签
- javascript - 启用数据表警告警报
- java - 所有字符串都是“???” 从对象类型的 Oracle 中检索表时