2

I am working with the google maps API and I am trying to convert the map object into a JSON string to store it in local storage. For some reason when I run this block of code the second console.log never runs and when I look in local storage it still says [object Object] meaning the JSON.strigify() never worked.

map = new window.google.maps.Map(document.getElementById('map'), {
    center: this.state.center,
    zoom: 8.5
});
console.log(map);
let jsonMap = JSON.stringify(map);
console.log(jsonMap);

I could be missing something very obvious but I just can't see it.

Cheers,

Josh Bowden
  • 892
  • 3
  • 12
  • 28
  • I'm not familiar with the google maps API; What does `map` actually return? Are you 100% sure it is a JSON object? Could it be something else (Possibly an array?). Try running `console.log("type of map: ", typeof map);` and see that that returns. – Magnum Oct 05 '18 at 16:10
  • Interesting I did that and nothing was console logged. That doesn't seem right. – Josh Bowden Oct 05 '18 at 16:30
  • What happens if you wrap it in a Try/Catch? Could there be a circular reference in map? – Ryan Bennett Oct 05 '18 at 16:59
  • I wrapped it in a try catch and there is still no response which is even weirder. I am going to run through the debugger a number more times. – Josh Bowden Oct 05 '18 at 17:04

1 Answers1

2

You will get a type error trying to stringify the map. It is pretty complex in structure and content.

Why are you trying to save it to a local storage anyway? You would be better saving the options that build the map instead of the map object itself i.e. latitude, longitude, zoom etc.

If you really need to go down the stringify route check this post out:

JSON.stringify, avoid TypeError: Converting circular structure to JSON

Tom_B
  • 307
  • 2
  • 8
  • I am trying to save it in localStorage for use offline. The circular structure is the tricky bit that I need to learn. Thank you for that suggestion. – Josh Bowden Oct 05 '18 at 17:09
  • ah I see! Out of interest, do you plan on allowing the user drag the map - i.e. how would you load new map tiles if they are offline – Tom_B Oct 05 '18 at 17:43
  • So I don't think that would be possible. I am looking into static maps for offline but I am not sure how the markers would remain. – Josh Bowden Oct 05 '18 at 18:11
  • Static maps was going to be my suggestion. I think it is possible to pass in marker data in the static map URL request although I haven't done that myself – Tom_B Oct 05 '18 at 19:48
  • Yes you can add it in but I think there isn't an option for interactivity with that marker. – Josh Bowden Oct 08 '18 at 13:29
  • Hmm yeah that does make sense. It is possible to convert a lat long to a pixel, doing that might help you work out where the markers are displayed on the map image. You could then create clickable elements from that – Tom_B Oct 08 '18 at 14:32