Reputation: 211
I have this javascript result:
var layer = '{"type":"polygon", "coordinates": "-34.32982832836202 149.88922119140625, -34.80027235055681 149.80682373046875, -34.74161249883173 150.30120849609375, -33.99802726234876 150.77362060546875, -33.97980872872456 150.27923583984375"}';
I checked it against JSONlint.com and was told it is a valid JSON string.
why can't JSON.parse()
and JSON.stringify()
not work.
I'm being told by the console that JSON.parse()
and JSON.stringify
are not recognized functions.
Thanks.
ok. let me try this again. Sorry, was given bad info.
var polygon = new Array();
polygon.push('{"type":"polygon", "coordinates": "-34.32982832836202 149.88922119140625, -34.80027235055681 149.80682373046875, -34.74161249883173 150.30120849609375, -33.99802726234876 150.77362060546875, -33.97980872872456 150.27923583984375"}');
var layer = polygon[0] //should be of value of string just stored
console.log(layer); //correctly displays JSON string
console.log(JSON.parse(layer)); //line that errors.
this is a portion of the full code below:
// This example requires the Drawing library. Include the libraries=drawing
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=drawing">
var selectedShape;
var drawingManager;
var names = [];
var polygons = new Array();
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: -34.397,
lng: 150.644
},
zoom: 8
});
drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.POLYGON,
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: ['circle', 'polygon', 'rectangle']
},
polygonOptions: {
editable: true,
draggable: true
},
circleOptions: {
editable: true,
draggable: true
},
rectangleOptions: {
editable: true,
draggable: true
}
});
drawingManager.setMap(map);
//load preset data
function setJSON(Shape) {
console.log(Shape.type);
if (Shape.type === "circle") {
return '{"type":"'+Shape.type +'", "lat":"'+Shape.getCenter().lat()+'", "lng":"'+Shape.getCenter().lng()+'", "radius":"'+Shape.getRadius()+'" }';
}
if (Shape.type === "rectangle"){
return '{"type":"' + Shape.type + ', "start":"'+ Shape.getBounds().getNorthEast() +'", "end":"'+ Shape.getBounds().getSouthWest() +'"}';
}
if (Shape.type === "polygon"){
//eturn '{"type":"'+ Shape.type +'"}' + Shape.getPaths();
vertice = Shape.getPath();
console.log("vertice count: " + vertice.getLength());
JSON = '{"type":"'+ Shape.type +'", "coordinates": "';
vertice.forEach(function(xy, i) {
JSON = JSON + xy.lat() + ' ' + xy.lng() + ', ';
});
JSON = JSON.slice(0,-2) + '"}';
return JSON;
}
return 0
}
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(event) {
drawingManager.setMap(null);
var newShape = event.overlay;
newShape.type = event.type;
selectedShape = newShape;
console.log(setJSON(selectedShape));
if (newShape.type === "circle" || newShape.type === "rectangle") {
google.maps.event.addListener(selectedShape, 'bounds_changed', function(event){
console.log(setJSON(selectedShape));
});
}
if (newShape.type === "polygon") {
google.maps.event.addListener(selectedShape.getPath(), 'set_at', function(event) {
// complete functions
console.log(setJSON(selectedShape));
});
google.maps.event.addListener(selectedShape.getPath(), 'insert_at', function(event) {
// complete functions
console.log(setJSON(selectedShape));
});
google.maps.event.addListener(selectedShape, 'rightclick', function(event) {
// Check if click was on a vertex control point
if (event.vertex === undefined) {
return;
}
deleteMenu.open(map, selectedShape.getPath(), event.vertex);
console.log('right-click');
})
}
function DeleteMenu() {
this.div_ = document.createElement('div');
this.div_.className = 'delete-menu';
this.div_.innerHTML = 'Delete';
var menu = this;
google.maps.event.addDomListener(this.div_, 'click', function() {
menu.removeVertex();
});
}
DeleteMenu.prototype = new google.maps.OverlayView();
DeleteMenu.prototype.onAdd = function() {
var deleteMenu = this;
var map = this.getMap();
this.getPanes().floatPane.appendChild(this.div_);
// mousedown anywhere on the map except on the menu div will close the
// menu.
this.divListener_ = google.maps.event.addDomListener(map.getDiv(), 'mousedown', function(e) {
if (e.target != deleteMenu.div_) {
deleteMenu.close();
}
}, true);
};
DeleteMenu.prototype.onRemove = function() {
google.maps.event.removeListener(this.divListener_);
this.div_.parentNode.removeChild(this.div_);
// clean up
this.set('position');
this.set('path');
this.set('vertex');
};
DeleteMenu.prototype.close = function() {
this.setMap(null);
};
DeleteMenu.prototype.draw = function() {
var position = this.get('position');
var projection = this.getProjection();
if (!position || !projection) {
return;
}
var point = projection.fromLatLngToDivPixel(position);
this.div_.style.top = point.y + 'px';
this.div_.style.left = point.x + 'px';
};
DeleteMenu.prototype.open = function(map, path, vertex) {
this.set('position', path.getAt(vertex));
this.set('path', path);
this.set('vertex', vertex);
this.setMap(map);
this.draw();
};
DeleteMenu.prototype.removeVertex = function() {
var path = this.get('path');
var vertex = this.get('vertex');
if (!path || vertex == undefined) {
this.close();
return;
}
path.removeAt(vertex);
this.close();
};
var deleteMenu = new DeleteMenu();
});
google.maps.event.addDomListener(document.getElementById('btnClear'), 'click', function(event) {
selectedShape.setMap(null);
drawingManager.setMap(map);
});
google.maps.event.addDomListener(document.getElementById('save'), 'click', function(event) {
names.push($('#polyname').val());
polygons.push(setJSON(selectedShape));
length = names.length;
console.log(length);
console.log("name: " + names[length-1] + "; polygon: " + polygons[length-1]);
});
google.maps.event.addDomListener(document.getElementById('btnrecall'), 'click', function(event) {
$('#btnClear').click();
console.log($('#btnLoad').val());
var namefield = $('#btnLoad').val();
if (namefield !== undefined){
var polyid = names.indexOf(namefield);
if (polyid > -1) {
var layer = polygons[polyid];
console.log(layer);
console.log(JSON.parse(JSON.stringify(layer)));
}else {
alert("no polygon by that name. Please Try again");
}
}else {
alert("please enter a name to continue.");
}
});
}
Upvotes: 0
Views: 6247
Reputation: 211
Apparently, while putting code in at Update #1 above, another question I had placed in stackoverflow had a direct impact on the reason for this question.
why am I getting type errors when hovering over map after layers are set?
as such, I had a variable I called JSON
elsewhere in the code. using JSON
as a variable overridden all of the global JSON
directives, which denied access to the parse
function.
Thanks all guys.
Upvotes: 1
Reputation: 1823
var layer = '{"type":"polygon", "coordinates": "-34.32982832836202 149.88922119140625, -34.80027235055681 149.80682373046875, -34.74161249883173 150.30120849609375, -33.99802726234876 150.77362060546875, -33.97980872872456 150.27923583984375"}';
$(document).ready(function() {
// here you can directly use it as a string no need of JSON.Stringify();
$("#string").text(layer);
// here it is parsed as a JSON and works just fine
$someVar = JSON.parse(layer);
$("#object").text($someVar.type);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="string"></p>
<p id="object"></p>
The variable that you have provided in your question is already a string, so you do not need the use of JSON.Stringify()
. You can use it directly as a string. Otherwise in the code snippet I have managed to use JSON.Parse()
with no problem. Maybe try and check your code and compare it with the example?
Hope this helps you out
Upvotes: 0
Reputation: 22534
I am able to parse it. Check here. You can refer to this for browser issue with JSON in IE.
var layer = '{"type":"polygon", "coordinates": "-34.32982832836202 149.88922119140625, -34.80027235055681 149.80682373046875, -34.74161249883173 150.30120849609375, -33.99802726234876 150.77362060546875, -33.97980872872456 150.27923583984375"}';
console.log(JSON.parse(layer));
Upvotes: 0