我有一个从pg_query返回的地址,我已经转换为纬度和经度值。然后我有javascript利用这些值将地图标记放在谷歌地图上。我收到以下错误:
VM884:1 Uncaught SyntaxError: Unexpected token [ in JSON at position 35
at JSON.parse (<anonymous>)
at XMLHttpRequest.xhr.onreadystatechange (map.php:37)
JSON编码数据是:
[{"lat":43.66852,"lng":-70.245084}][{"lat":43.66852,"lng":-70.245084}]
这是PHP:
$arr = array();
while ($markers = pg_fetch_row($address)){
$request_url = "http://maps.googleapis.com/maps/api/geocode/xml?address=".$markers[0]."&sensor=true";
$xml = simplexml_load_file($request_url) or die("url not loading");
$status = $xml->status;
if ($status=="OK") {
$arr = array();
$Lat = (float)$xml->result->geometry->location->lat;
$Lng = (float)$xml->result->geometry->location->lng;
$arr[] = array("lat" => $Lat, "lng" => $Lng);
}
echo json_encode($arr);
这是JS:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: {lat: 39.350033, lng: -94.6500523}
});
// Do not actually need labels for our purposes, but the site_id is best if they are required.
var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
// Add some markers to the map.
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
console.log(xhr.responseText);
if (xhr.readyState == 4) {
var arr = JSON.parse(xhr.responseText);
console.log(xhr.responseText);
if(Array.isArray(arr)){
showMarkers(arr);
}
}
}
xhr.open('GET', 'markers.php', true);
xhr.send();
function showMarkers(locations){
var markers = locations.map(function(location, i) {
return new google.maps.Marker({
position: location,
label: labels[i % labels.length]
});
});
var markerCluster = new MarkerClusterer(map, markers, {imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png'});
}
}
答案 0 :(得分:2)
您的json响应需要像这样
[{"lat":43.66852,"lng":-70.245084},{"lat":43.66852,"lng":-70.245084}]
和php
$arr = array();
while ($markers = pg_fetch_row($address)){
$request_url = "http://maps.googleapis.com/maps/api/geocode/xml?address=".$markers[0]."&sensor=true";
$xml = simplexml_load_file($request_url) or die("url not loading");
$status = $xml->status;
if ($status=="OK") {
$Lat = (float)$xml->result->geometry->location->lat;
$Lng = (float)$xml->result->geometry->location->lng;
$arr[] = array("lat" => $Lat, "lng" => $Lng);
}
}
echo json_encode($arr);