【问题标题】:Use Google Maps API to get City from Zip code and then write it to JSON?使用 Google Maps API 从邮政编码获取城市,然后将其写入 JSON?
【发布时间】:2017-10-06 18:00:36
【问题描述】:

我有一个带有一堆不同邮政编码的 JSON 文件。我想做的是利用 Google Maps API 检索与邮政编码关联的城市,然后将其写入 JSON 文件。

到目前为止,我有一个脚本可以正确地从结果中获取城市。我将如何将这些城市写入 JSON 文件?

这是我的 JSON 数据:

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

这是我的脚本:

$(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

更新:

我找到了一种使用 NodeJS from this question 写入我的 JSON 文件的方法,下面的代码成功地将我的每个 JSON 对象的“City”更新为“test”,现在我想我只需要帮助将其合并到我的 jQuery 代码:

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));

如果这样更容易的话,我也愿意使用 PHP。

又一次尝试(最接近我的尝试):

计划是仅使用此脚本一次以使用所有城市填充 JSON。所以我想我会尝试在客户端做这件事,我可以在其中注销一些 JSON 数据,然后手动复制/粘贴它,而不是依赖服务器端代码为我做这件事。这让我想到了这个解决方案:

$(function() {
			var item = [];
			var locations = [
			  {
			    "State": "Oklahoma",
			    "ZIP": "73169",
			    "City": ""
			  },
			  {
			    "State": "Oklahoma",
			    "ZIP": "73169",
			    "City": ""
			  },
			  {
			    "State": "Oklahoma",
			    "ZIP": "73170",
			    "City": ""
			  },
			  {
			    "State": "Oklahoma",
			    "ZIP": "73172",
			    "City": ""
			  },
			  {
			    "State": "Oklahoma",
			    "ZIP": "73173",
			    "City": ""
			  }
			];

		    $.each(locations, function(i, item) {
				var zip = item.ZIP;
				var url = "https://maps.googleapis.com/maps/api/geocode/json?address=" + zip + "&key=AIzaSyA75wif8_yewifGSqVFnR3U50zuW_EnAns";
				$.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];
						item.City = city;
						console.log(item);
					}
				});
		    });
});
&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

如果我在for 语句中注销item,它会正确返回所有内容。如何将其输出为 JSON 格式的单个数组?

【问题讨论】:

  • 想解释一下否决票?
  • 您是否尝试在客户端 JavaScript 中创建和保存文件(即在浏览器中运行)?
  • 文件的保存方式或保存位置并不重要,我只会运行一次以将城市填充到 JSON 文件中,然后不再使用它。即使我可以在客户端修改 JSON 并能够将其复制/粘贴到 JSON 文件中,这也足够了。

标签: javascript json node.js google-maps


【解决方案1】:

您不能直接从浏览器写入文件。您可以创建一个 blob 或一个数据 URL,并提供一个可以下载文件的链接,例如 in this example

或者,既然你有 Node.js,也许只是在 shell 中运行一个脚本。此示例需要 npm install request request-promise-native,但您可以使用 Node.js https API 代替。此外,示例中没有错误处理。

const fs = require('fs');
const http = require('http');
const request = require('request-promise-native');

const baseUrl = 'https://maps.googleapis.com/maps/api/geocode/json?key=<your key>&address=';
const locations = JSON.parse(fs.readFileSync('locations.json', 'utf8'));

Promise.all(locations.map((location) => {
  return request
    .get(baseUrl + location.ZIP)
    .then((result) => {
      location.city = JSON.parse(result).results[0].formatted_address.split(',', 1)[0];
      return location;
    });
})).then((results) => {
  fs.writeFileSync('results.json', JSON.stringify(results));
});

编辑:我刚刚阅读了您关于即使复制粘贴对您来说也足够的评论。您也可以在浏览器中使用上述方法,无需 jQuery:

Promise.all(locations.map((location) => {
  return fetch(baseUrl + location.ZIP)
    .then((result) => {
      location.city = result.results[0].formatted_address.split(',', 1)[0];
      return location;
    });
})).then((results) => {
  console.log(JSON.stringify(results));
});

【讨论】:

    猜你喜欢
    • 2011-01-19
    • 2012-07-08
    • 2011-11-28
    • 2013-04-05
    • 2011-07-31
    • 2015-01-03
    • 2013-05-30
    • 2013-04-08
    • 2015-06-29
    相关资源
    最近更新 更多