Monday, 8 May 2017

Use Google Maps API to get City from Zip code and then write it to JSON?

I have a JSON file with a bunch of different zip codes. What I want to do is leverage the Google Maps API to retrieve the City associated with a zip code, and then write it to the JSON file.

So far I have a script which is correctly grabbing the city from the results. How would I go about writing these cities to the JSON file?

Here's my JSON data:

[
  {
    "State": "Oklahoma",
    "ZIP": 73169
  },
  {
    "State": "Oklahoma",
    "ZIP": 73169
  },
  {
    "State": "Oklahoma",
    "ZIP": 73170
  },
  {
    "State": "Oklahoma",
    "ZIP": 73172
  },
  {
    "State": "Oklahoma",
    "ZIP": 73173
  }
]

And here's my script:

$(function() {
  $.get('locations.json', function(data) {
    $.each(data, function(i, item) {
      var zip = item.ZIP;
      var url = "https://maps.googleapis.com/maps/api/geocode/json?address=" + zip + "&key=AIzaSyD_YqB4d_-xKcmNP9jJCiPkJYDS8J3f6pI";
      $.get(url, function(loc) {
          for(var i=0;i<loc.results.length;i++) {
            var address = loc.results[i].formatted_address;
            var city = address.split(',', 1)[0]
            console.log(city);
          }
      });
    });
  });
});

Here's a Plunker

UPDATE:

I found a way to write to my JSON file using NodeJS from this question, the code below successfully updates the "City" to "test" for each of my JSON objects, now I guess I just need help on incorporating this into my jQuery code:

fs = require('fs');
var m = JSON.parse(fs.readFileSync('locations.json').toString());
m.forEach(function(p){
    p.City = "test";
});
fs.writeFile('locations.json', JSON.stringify(m));



via user13286

No comments:

Post a Comment