首页 > 解决方案 > 如何解决 InvalidValueError: at index 0: not a LatLng or LatLngLiteral: not an Object?

问题描述

我正在尝试在谷歌地图中制作一条折线,但我首先在我的数据库中检索数据。然后到我的 php 文件和我的脚本文件。以下是我如何在我的 DBPHPfile 中生成我的 json 数据。抱歉,如果它有点乱

while($row = pg_fetch_assoc($result)){
    $cleaned = clean($row['longlat']);
    $count =true;
    $temp = 0;
    $temp2 = 0;

    for($x = 0; $x <= strlen($cleaned)-1; $x++){
      if($cleaned[$x] == ' '){
        $temp2 = $x - $temp;
        if($count == true){
          array_push($long, remove_spaces(substr($cleaned, $temp, $temp2)));
          $count = false;
        }
        else{
          $count = true;
          array_push($lat, remove_spaces(substr($cleaned, $temp, $temp2)));
        }
        $temp = $x;

      }
    }
    $temp2 = strlen($cleaned) - $temp;
    array_push($lat, substr($cleaned, $temp, $temp2+1));
  }


  $finalroutes = array();

  // finalizing my routes

  for($x = 0; $x<sizeof($long);$x++){
    $long[$x]=remove_spaces($long[$x]);
    settype($long[$x], "float");
    $lat[$x]=remove_spaces($lat[$x]);
    settype($lat[$x], "float");
    array_push($finalroutes, "{lat: $lat[$x], lng: $long[$x]}");
  }
   echo json_encode($finalroutes);

那么我的脚本是这样的

$(function(){
      $('#go').click(function(){
        var longtemp = $('#long').val();
        var lattemp = $('#lat').val();

        $.ajax({
          url:"dbphp.php",
          method:"POST",
          data:{longtemp:longtemp, lattemp:lattemp},
          success:function(data){
              map = new google.maps.Map(document.getElementById('map'), {zoom: 18, center: {lat: 8.264670, lng: 124.263394}, mapTypeId: 'terrain'});
              flightPlanCoordinates = JSON.parse(data); //from here
              // var newflights=[];
              // for(var i = 0; i <flightPlanCoordinates.type.length();i++)
              //   newflights[i]=flightPlanCoordinates[i];
              console.log(data);


              flightPath = new google.maps.Polyline({
                path: flightPlanCoordinates,
                geodesic: true,
                strokeColor: '#FF0000',
                strokeOpacity: 1.0,
                strokeWeight: 2
              });//to here
              flightPath.setMap(map);
          }
        })
      })
    })

我标记了问题所在,以便您轻松找到它。

标签: javascriptphpajax

解决方案


替换这个:

array_push($finalroutes, "{lat: $lat[$x], lng: $long[$x]}");

$finalroutes[] = ["lat" => $lat[$x], "lng" => $long[$x]];

这样您将拥有正确的数组,稍后您将被编码为 jsonecho json_encode($finalroutes);


推荐阅读