Search code examples
javascriptjsonhtmljquery-ui-map

Create JSON array from HTML5 localstorage items


I'm using the jquery ui map in my cordova iOS app, and need to encode all my database results (latitudes and longitudes) in JSON. I already set the localstorage element, and know I received the correct response, but I dont know how to encode all the results into a JSON array. I've tried using a for loop, but I must have done it incorrectly because my code then failed. One more thing, I know that the map works, and also that adding markers work, but I used the demo json array. I need to create my own array with my own objects, and dont know how to. Thanks for the help.

MAP.HTML

    <script type="text/javascript">
        $(document).ready(function() {
                $('#map_canvas').gmap().bind('init', function(evt, map) {
                    $('#map_canvas').gmap('getCurrentPosition', function(position, status) {
                        if ( status === 'OK' ) {
                            var clientPosition = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
                            $('#map_canvas').gmap('addMarker', {'position': clientPosition, 'bounds': true});
                            $('#map_canvas').gmap('addShape', 'Circle', {
                                'strokeWeight': 0,
                                'fillColor': "#008595",
                                'fillOpacity': 0.25,
                                'center': clientPosition,
                                'radius': 15,
                                'clickable': false
                            });
                        }
                    });
                });
                var name = localStorage.getItem("name");
                var lat = localStorage.getItem("lat");
                var lon = localStorage.getItem("lon");
                var it = localStorage.getItem("it");

                alert(lat);
            });
        </script>

Solution

  • You need to convert your JSON object to string and store the string.
    Use JSON.stringify(yourObject) to convert to string and JSON.parse([your Object from localstorage]).
    See similar question