<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>雪道屋 &#124; Snow on rails blog &#187; javascript</title>
	<atom:link href="http://blog.snowonrails.com/categories/javascript/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.snowonrails.com</link>
	<description>life.each{&#124;day&#124; day.live_well!}</description>
	<lastBuildDate>Thu, 11 Feb 2010 07:03:12 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9-rare</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>应用google map api 找出附近城市</title>
		<link>http://blog.snowonrails.com/2008/09/24/%e5%ba%94%e7%94%a8google-map-api-%e6%89%be%e5%87%ba%e9%99%84%e8%bf%91%e5%9f%8e%e5%b8%82/</link>
		<comments>http://blog.snowonrails.com/2008/09/24/%e5%ba%94%e7%94%a8google-map-api-%e6%89%be%e5%87%ba%e9%99%84%e8%bf%91%e5%9f%8e%e5%b8%82/#comments</comments>
		<pubDate>Wed, 24 Sep 2008 04:00:02 +0000</pubDate>
		<dc:creator>snow</dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[google map api]]></category>

		<guid isPermaLink="false">http://blog.snowonrails.com/?p=82</guid>
		<description><![CDATA[最近的一个项目中有这么一个功能需求，在搜索一个城市的某些记录的时候后，要将该城市附近城市的类似数据也现实出来。于是上网google一下，希望有相关api能够提供输入城市名称返回附近城市的列表的功能，找了半天似乎也没有类似api，只找到一个 Urban Mapping 不过是提供neighborhoods 查找功能的（其实neighborhoods应该是更为合理的，不过似乎客户就是想显示临近的city），没办法，只能又回到了google map,既希望于能找出一些可用的api。之前应用google map的场景也不少，但是都没有接触过GDirection这个类，这次又仔细了看了一遍api,发现似乎可以利用这个类来达到我的目的。主要思想就是，首先找出你要用到的所有城市(我们这里是CA Bay Area 附近的所有城市)，然后一次调用gmap的接口,发送类似 “from: ** to: ** ”这样的query 给gdirection, 然后通过在回调方法load中调用getDistance方法来获得两个城市之间的距离，这样我们就可以任意的定义&#8221;nearby&#8221;的距离，然后根据获得的distance来判断一个城市是否是另一个城市的&#8221;nearby city&#8221;.
这个解决方法的关键步骤就在于如何将所有的city两两之间的距离自动发送给gmap api,然后返回结果。一开始我也没多想，就循环呗，于是循环调用api 发送和回调代码，大概是这个样子的：
function initialize(){
...
	while(cities.length&#62;0){
		city = cities.shift();
		index = 0
		for(c in cities){
			direction = new GDirections();
			query = "from: "+city+" to: "+cities[c]
			direction.load(query);
			listen(direction,city,cities[c]);
		}
	 }
...
}
// 回调方法
function listen(){...}
结果代码出了几个问题：

只运行了几个结果就报错跳出了
browser会提示脚本运行会使browser变慢
由于连续的发放请求，被google认为使spam，会将api key停止是用一会。

经过一番尝试想到从一下几个方面解决此问题：

由于回调代码是异步的而且不能保证执行的顺序所以造成循环调用的时候报错，要解决此问题，必须保证query“一个接一个”的发送，发送一个query-执行回调代码完成－再发送下一个query。因此不能是用简单的循环来做此事，重构上述代码用递归的方式运行
将每一发送的时间间隔提高，防止被google当作spam，配合prototype的periodicalexecuter使用，效果甚佳。

下面给出完整的rhtml页面代码


	
		
		
		
		
		
		
		google.load("maps", "2.x");
		var cities = new Array();
		var results = new Array();
		var city = '';
		
		cities.push('');
		
		var map = null;
		function initialize() {
		 [...]]]></description>
			<content:encoded><![CDATA[<p>最近的一个项目中有这么一个功能需求，在搜索一个城市的某些记录的时候后，要将该城市附近城市的类似数据也现实出来。于是上网google一下，希望有相关api能够提供输入城市名称返回附近城市的列表的功能，找了半天似乎也没有类似api，只找到一个 <a href="http://developer.urbanmapping.com/demo" target="_blank">Urban Mapping</a> 不过是提供neighborhoods 查找功能的（其实neighborhoods应该是更为合理的，不过似乎客户就是想显示临近的city），没办法，只能又回到了google map,既希望于能找出一些可用的api。之前应用google map的场景也不少，但是都没有接触过GDirection这个类，这次又仔细了看了一遍api,发现似乎可以利用这个类来达到我的目的。主要思想就是，首先找出你要用到的所有城市(我们这里是CA Bay Area 附近的所有城市)，然后一次调用gmap的接口,发送类似 “from: ** to: ** ”这样的query 给gdirection, 然后通过在回调方法load中调用getDistance方法来获得两个城市之间的距离，这样我们就可以任意的定义&#8221;nearby&#8221;的距离，然后根据获得的distance来判断一个城市是否是另一个城市的&#8221;nearby city&#8221;.</p>
<p>这个解决方法的关键步骤就在于如何将所有的city两两之间的距离自动发送给gmap api,然后返回结果。一开始我也没多想，就循环呗，于是循环调用api 发送和回调代码，大概是这个样子的：</p>
<pre lang="javascript">function initialize(){
...
	while(cities.length&gt;0){
		city = cities.shift();
		index = 0
		for(c in cities){
			direction = new GDirections();
			query = "from: "+city+" to: "+cities[c]
			direction.load(query);
			listen(direction,city,cities[c]);
		}
	 }
...
}
// 回调方法
function listen(){...}</pre>
<p>结果代码出了几个问题：</p>
<ol>
<li>只运行了几个结果就报错跳出了</li>
<li>browser会提示脚本运行会使browser变慢</li>
<li>由于连续的发放请求，被google认为使spam，会将api key停止是用一会。</li>
</ol>
<p>经过一番尝试想到从一下几个方面解决此问题：</p>
<ol>
<li>由于回调代码是异步的而且不能保证执行的顺序所以造成循环调用的时候报错，要解决此问题，必须保证query“一个接一个”的发送，发送一个query-执行回调代码完成－再发送下一个query。因此不能是用简单的循环来做此事，重构上述代码用递归的方式运行</li>
<li>将每一发送的时间间隔提高，防止被google当作spam，配合prototype的periodicalexecuter使用，效果甚佳。</li>
</ol>
<p>下面给出完整的rhtml页面代码</p>
<pre lang="javascript">
<html>
	<head>
		<%= javascript_include_tag "prototype"%>
		<script src="http://www.google.com/jsapi?key=YOUR_API"
		  type="text/javascript"></script>
		<script type="text/javascript" charset="utf-8">
		<!-- =================================== -->
		<!-- = Google map related code begin = -->
		<!-- =================================== -->
		google.load("maps", "2.x");
		var cities = new Array();
		var results = new Array();
		var city = '';
		<% City.find(:all).each do |c| %>
		cities.push('<%= c.name %>');
		<% end %>
		var map = null;
		function initialize() {
		  if (GBrowserIsCompatible()) {
		    map = new google.maps.Map2(document.getElementById("google_map")); 	
			geocoder = new google.maps.ClientGeocoder();
			find_distance();	
		  }
		}

		function listen(direction,from,to){
			GEvent.addListener(direction, "load", 
				function(){
					if(direction.getStatus().code==200){
					results.push({from: from, to: to, distance: direction.getDistance().meters });
					$('distance').innerHTML+= (from+"--"+to+": "+direction.getDistance().meters+"<br/>");
					}
				}
			);
		}

		function find_distance(){
			city = cities.shift();
			var index = 0;

			new PeriodicalExecuter(function(pe) {
				direction = new GDirections();
				query = "from: "+city+", CA to: "+cities[index]+", CA"				
				direction.load(query);										
				listen(direction,city,cities[index]);
				index++
				if(index==cities.length){
					pe.stop();
					if(cities.length>1){find_distance();}
				}
			},0.2);
		}
		google.setOnLoadCallback(initialize);
		</script>
		<title></title>
	</head>
	<body>
<div id="google_map" style="width:400px;height:400px" ></div>

		Distance:
<div id="distance">0</div>

		<%= link_to_remote "Load results", :url=>{:controller=>'home',:action=>'save_distances',:method=>"post"},:with=>"'results='+results.toJSON()" %>
	</body>
</html></pre>
<p>PS: <a href="http://gigix.thoughtworkers.org/2008/9/23/replace-long-calculation-with-asynch" target="_blank">这篇文章</a>和上述解决方案有神似的地方，基本上讲的一回事.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.snowonrails.com/2008/09/24/%e5%ba%94%e7%94%a8google-map-api-%e6%89%be%e5%87%ba%e9%99%84%e8%bf%91%e5%9f%8e%e5%b8%82/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
