You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python提取JavaScript代码中GLatLng坐标的问题求助

解决从JavaScript代码中提取GLatLng坐标的问题

Hey there! Since you're just starting out with Python and hitting a snag pulling those coordinates from the downloaded JS code—don't worry, this is a perfect job for regular expressions, and we don't need to rely on fixed line numbers at all.

思路分析

Your target coordinates are wrapped in a GLatLng() constructor call, like new GLatLng(51.6663267, 39.1898874). Instead of targeting specific lines, we can write a regex pattern that matches this structural pattern regardless of where it appears in the code.

Python实现代码

Here's a straightforward script using the re module that will reliably extract those coordinates:

import re

# 把你的JavaScript代码存成字符串(这里直接用你提供的代码内容)
js_script = """var map_shop = null; var marker_shop = null; function google_maps_shop_initialize() { if (GBrowserIsCompatible()) { map_shop = new GMap2(document.getElementById("map_canvas_shop")); point_center = new GLatLng(51.6663267, 39.1898874); marker_shop = new GMarker(point_center); map_shop.addOverlay(marker_shop); map_shop.setCenter(point_center, 13); //Create new Tile Layer var gTileUrlTemplate = '//mt1.google.com/vt/lyrs=m@121,transit|vm:1&hl=ru&opts=r&x={X}&y={Y}&z={Z}'; var tileLayerOverlay = new GTileLayerOverlay( new GTileLayer(null, null, null, { tileUrlTemplate: gTileUrlTemplate, isPng:true, opacity:1 }) ); map_shop.addOverlay(tileLayerOverlay); } } google_maps_shop_initialize();"""

# 正则模式:匹配new GLatLng(数字, 数字)的结构
coord_pattern = r'new GLatLng\(([\d.]+),\s*([\d.]+)\)'

# 搜索匹配内容
match_result = re.search(coord_pattern, js_script)

if match_result:
    # 提取第一个捕获组(纬度)和第二个捕获组(经度)
    latitude = match_result.group(1)
    longitude = match_result.group(2)
    print(f"提取到的坐标:{latitude}, {longitude}")
else:
    print("未找到符合格式的坐标")

正则模式解释

Let's break down the regex r'new GLatLng\(([\d.]+),\s*([\d.]+)\)' so you understand how it works:

  • new GLatLng\(: Matches the literal text new GLatLng( (we escape the parenthesis with \ because it's a special regex character)
  • ([\d.]+): Captures one or more digits or decimal points (this is your latitude value)
  • ,\s*: Matches a comma followed by zero or more whitespace characters (handles spaces, tabs, or even line breaks between the coordinates)
  • ([\d.]+): Captures the second coordinate (longitude)
  • \): Matches the closing parenthesis

This pattern is flexible enough to handle variations in spacing around the comma, so it works even if the code is formatted differently than your example.

内容的提问来源于stack exchange,提问作者Janek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:56:17