注意:将数组从 php 转换为 javascript 时出现数组到字符串的转换错误

Notice: Array to string conversion error when converting array from php to javascript

本文关键字:转换 数组 字符串 错误 php 注意 javascript      更新时间:2023-09-26

我正在尝试从数据库正在检索的 php 数组中获取$lat和$long的纬度和经度数组。

<?php
...
$lat[$latlongindex] = $results_row['latitude'];
$long[$latlongindex] = $results_row['longitude'];

echo "
<script type='"text/javascript'">
        var locations = $latlongindex;
        var jslat = <?php echo json_encode($lat); ?>;
        var jslong = <?php echo json_encode($long); ?>; // <----------Line 58
        var map = new GMaps({
            div: '#map',
            lat: 39.833,
            lng: -98.583,
            width: '900px',
            height: '500px',
            zoom: 4,
            zoomControl : true,
            zoomControlOpt: {
            style : 'SMALL',
            position: 'TOP_LEFT'
            },
            panControl : false,
        });
//------------------------------------------------ADD MARKERS--------------
        for (var i = 0; i<locations; i++) {
            map.addMarker({
            position: new google.maps.LatLng( jslat[i], jslong[i] ),
            });
        }
</script>
"; // <--------------------------------Line 83
}
}
?>

作为快速检查,我可以回显 json_encode($lat) 和 json_encode($long) 并且它们显示正确,但是当我尝试在 javascript 中使用它们时,我得到"注意:数组到字符串的转换"在第 58 行和第 83 行。如果我明确说明位置,例如:

        var jslat = [];
        jslat[0] = $lat[0];

它将正常运行,但显然只显示第一个标记。因此,我知道我可以访问$lat数组和$long数组的元素。我觉得这是一个简单的错误,但似乎在堆栈上找不到任何类似问题的内容。

任何帮助都会很棒。谢谢。

// MAP CODE
        $qry_country_map = 'Select name, refugee, lat, lng FROM '.$table_name.' WHERE 1 AND status = 1';
        $country_data_map = $wpdb->get_results($qry_country_map , ARRAY_A);
        //echo "<pre>";print_r($country_data_map);exit;
        $array_string = "["; 
        for($m=0;$m<count($country_data_map);$m++) { 
         $array_string .= "['".$country_data_map[$m]['name']."', '".$country_data_map[$m]['name']."','".$country_data_map[$m]['refugee']."','".$country_data_map[$m]['lat']."', '".$country_data_map[$m]['lng']."'],";
        }
        $array_string = substr($array_string, 0,-1);
        $array_string .= "]";
        ?>
        <style>
          #map{
            height: 400px;
          }
          a[href^="http://maps.google.com/maps"]{display:none !important}
          .gmnoprint a, .gmnoprint span {
              display:none;
          }
          .gmnoprint div {
              background:none !important;
          }
        </style>
        <script src="http://maps.google.com/maps/api/js?sensor=false"></script>
        <div id="map"></div>
        <script type="text/javascript">
            var marker_image = '<?php echo $plugin_image_url;?>';
            // Define your locations: HTML content for the info window, latitude, longitude
            var locations = <?php echo $array_string;?>;
            var map = new google.maps.Map(document.getElementById('map'), {
              center: new google.maps.LatLng(26.3351, 17.2283),
                  mapTypeControl: false,
                  scaleControl: false,
                  streetViewControl: false,
                  overviewMapControl: false,
                  panControl: false,
                  zoomControl: true,
                  zoomControlOptions: {
                    style: google.maps.ZoomControlStyle.SMALL
                  },
                  zoom: 2,
                  mapTypeId: google.maps.MapTypeId.ROADMAP
            });
            var styles = [
                    {
                        featureType: "landscape",
                        stylers: [
                            { visibility: "on" },
                            { color: "#FFFFFF"}
                        ]
                    },
                    {
                        featureType: "water",
                        stylers: [
                            { visibility: "on" },
                            { color: "#CCCCCC"}
                        ]
                    },
                    {
                       featureType: "administrative",
                       elementType: "geometry.fill",
                       stylers: [
                          { visibility: "off" }
                       ]
                    },
                    {
                        featureType: "all",
                        elementType: "labels",
                        stylers: [
                            { visibility: "off" }
                        ]
                    }
                  ];
                  map.setOptions({styles: styles});
            var infowindow = new google.maps.InfoWindow({
              maxWidth: 160 
            });
            var marker;  
            var markers = new Array();
            // Add the markers and infowindows to the map
            for (var i = 0; i < locations.length; i++) 
            {
                if(locations[i][3]!='' && locations[i][4]!='' && locations[i][2]!='')
                {
                    var scale;
                    if(locations[i][2]<100)
                        scale = locations[i][2];
                    else if(locations[i][2]>100 && locations[i][2]<500)
                        scale = locations[i][2]/25; 
                    else if(locations[i][2]>500 && locations[i][2]<1000)
                        scale = locations[i][2]/60;
                    else if(locations[i][2]>1000 && locations[i][2]<10000)
                        scale = locations[i][2]/275;     
                    else if(locations[i][2]>10000 && locations[i][2]<100000)
                        scale = locations[i][2]/1600;
                    else if(locations[i][2]>100000 && locations[i][2]<500000)
                        scale = locations[i][2]/7500;
                    else if(locations[i][2]>500000 && locations[i][2]<1000000)
                        scale = locations[i][2]/10500;  
                    scale = Math.round(scale);
                    if(scale!=0)
                    {
                        //console.log(scale);
                        marker = new google.maps.Marker({
                        position: new google.maps.LatLng(locations[i][3], locations[i][4]),
                        map: map,
                        icon: {
                        url: marker_image,
                        scaledSize: new google.maps.Size(scale, scale),
                        size:new google.maps.Size(scale, scale)
                        }
                        });
                      //ADD EVENT TO SHOW INFOWINDOW
                      google.maps.event.addListener(marker, 'mouseover', (function(marker, i) {
                        return function() {
                          infowindow.setContent(locations[i][0]);
                          infowindow.open(map, marker);
                          //marker.setIcon(new google.maps.MarkerImage('http://192.168.5.33/map-marker-hover.png'));
                          //marker.icon.scaledSize = new google.maps.Size(scale,scale);
                          //marker.icon.size = new google.maps.Size(scale,scale);
                        }
                      })(marker, i));
                      //ADD EVENT TO HIDE INFOWINDOW
                      google.maps.event.addListener(marker, 'mouseout', (function(marker, i) {
                        return function() {
                          infowindow.close(map, marker);
                          //marker.setIcon(new google.maps.MarkerImage('http://192.168.5.33/map-marker.png'));
                          //marker.icon.scaledSize = new google.maps.Size(scale,scale);
                          //marker.icon.size = new google.maps.Size(scale,scale);
                        }
                      })(marker, i));       
                    }
                }
            }
        </script> 

请参阅名为 $array_string 的变量,我已经在 php 中创建它,然后在 js 中回显以创建一个 js 数组,然后我循环使用 lat 和 long 来显示标记。

我已经为自定义标记图像和标记大小缩放编写了一些东西,具体取决于鼠标悬停和鼠标悬停的效果。

您只需要复制粘贴此代码进行细微更改即可完成。如果出现问题,请告诉我:)