2017-05-06 48 views
0

我想要做的是創建一個用戶腳本來將不同的GPS座標轉換爲一個超鏈接到谷歌地圖。將座標轉換爲谷歌地圖鏈接

我有一個網頁24.197611 N, 120.780512 E爲文本。我希望能夠點擊,爲了打開通往另一頁http://maps.google.com/maps?q=24.197611,120.780512

由於座標是括號內(14.495569 N,9.139927ē),我用的是這樣的:

$("div").html(function(i, html) { 
    return html.replace(/\((.+?)\)/g, "<a href='http://maps.google.com/maps?q=#$1'>$1</a>"); 
}); 

但鏈接也得到了大膽的部分。

回答

0

我建議您使用以下正則表達式中,你使用的格式相匹配的座標:

\((<b>)?(\d+\.\d+ [NEWS], \d+\.\d+) [NEWS](<\/b>)?\) 

在這種情況下,你有三個捕獲組。捕獲組#2與​​Google Maps超鏈接使用的格式中的座標相匹配。

下面是它如何與您提供的代碼工作:

$("div").html(function(i, html) { 
return html.replace(/\((<b>)?(\d+\.\d+ [NEWS], \d+\.\d+) [NEWS](<\/b>)?\)/g, "<a href='http://maps.google.com/maps?q=#$2'>$2</a>"); 
}); 
+0

紅色方向沒問題, 'http://maps.google.com/maps?q=24.197611 N,120.780512 E' 也可以,但如果使用粗體標籤,您的解決方案不起作用 – Kharg

+0

@Kharg我更新了答案。現在它應該適用於'(14.495569 N,9.139927 E)'和'(14.495569 N,9.139927 E)'。我強烈建議使用http://www.regexr.com/來創建和測試正則表達式。 –

0

所以,最後我用這樣的whick工作

function myFunction() { 
    $("div").each(function(i, html) { 
     var $this = $(this); 
     $this.html($this.html().replace(/((\d+\.\d+) [N], (\d+\.\d+) [E])/g, "<a href='http://maps.google.com/maps?q=$1' target='_blank'>$1</a>")); 
     }); 
    } 
    $(document).ready(myFunction); 
    setTimeout(myFunction, 2000); 

即使它似乎放緩事情