欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python調(diào)用高德地圖API實(shí)現(xiàn)JS網(wǎng)頁地圖顯示的完整代碼示例

 更新時(shí)間:2025年08月26日 08:44:30   作者:無人裝備硬件開發(fā)愛好者  
高德地圖提供了豐富的 API,可供開發(fā)者進(jìn)行地理信息的查詢和處理,這篇文章主要介紹了Python調(diào)用高德地圖API實(shí)現(xiàn)JS網(wǎng)頁地圖顯示的相關(guān)資料,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下

1 概述

本文將詳細(xì)介紹如何使用Python開發(fā)調(diào)用高德地圖API,并在JavaScript網(wǎng)頁中顯示地圖。我們將從基礎(chǔ)知識(shí)開始,逐步深入,最后提供一個(gè)完整的實(shí)現(xiàn)方案。內(nèi)容包括高德地圖API的申請(qǐng)、Python后端服務(wù)的開發(fā)、前端JavaScript地圖顯示以及前后端數(shù)據(jù)交互。文章將盡量使用表格方式呈現(xiàn)關(guān)鍵信息,確保內(nèi)容通俗易懂。

高德地圖API提供了豐富的地圖服務(wù),包括地理編碼逆地理編碼、路徑規(guī)劃地點(diǎn)搜索等功能3。通過Python調(diào)用這些API,我們可以實(shí)現(xiàn)地理位置數(shù)據(jù)的處理和分析,然后通過JavaScript在網(wǎng)頁上可視化展示結(jié)果。

1.1 高德地圖API簡介

高德地圖開放平臺(tái)為開發(fā)者提供了多種API服務(wù),主要包括:

  • Web服務(wù)API:提供地理編碼、逆地理編碼、路徑規(guī)劃等功能,可通過HTTP請(qǐng)求調(diào)用1。

  • JavaScript API:用于在網(wǎng)頁中顯示地圖、添加標(biāo)記、繪制圖形等2。

  • 其他API:如Android SDK、iOS SDK等,用于移動(dòng)應(yīng)用開發(fā)。

本文將重點(diǎn)介紹如何使用Python調(diào)用Web服務(wù)API處理地理數(shù)據(jù),以及如何使用JavaScript API在網(wǎng)頁中顯示地圖。

2 準(zhǔn)備工作

2.1 申請(qǐng)高德地圖API Key

使用高德地圖API前,需要申請(qǐng)API Key。具體步驟如下13:

  1. 注冊(cè)高德開發(fā)者賬號(hào)
    訪問高德開放平臺(tái),注冊(cè)賬號(hào)。

  2. 創(chuàng)建應(yīng)用
    登錄后進(jìn)入控制臺(tái),選擇"應(yīng)用管理" -> "我的應(yīng)用" -> "創(chuàng)建新應(yīng)用"。

  3. 添加Key
    在應(yīng)用詳情中點(diǎn)擊"添加Key",選擇"Web服務(wù)"作為服務(wù)平臺(tái)。如果需要在前端顯示地圖,還需創(chuàng)建一個(gè)Key并選擇"Web端(JSAPI)"作為服務(wù)平臺(tái)。

  4. 獲取Key
    創(chuàng)建成功后,將獲得一個(gè)API Key,后續(xù)調(diào)用API時(shí)需使用此Key。

2.2 安裝必要的Python庫

Python調(diào)用高德地圖Web服務(wù)API主要使用requests庫發(fā)送HTTP請(qǐng)求3。安裝命令如下:

bash

pip install requests

對(duì)于前端部分,我們需要使用HTML和JavaScript來顯示地圖。不需要額外安裝庫,只需在HTML中引入高德地圖JavaScript API即可。

3 Python調(diào)用高德地圖Web服務(wù)API

高德地圖Web服務(wù)API提供了多種功能,以下介紹幾個(gè)常用功能的調(diào)用方法。

3.1 地理編碼

地理編碼是將結(jié)構(gòu)化地址轉(zhuǎn)換為經(jīng)緯度坐標(biāo)的過程13。

API地址https://restapi.amap.com/v3/geocode/geo

請(qǐng)求參數(shù)

參數(shù)名含義是否必須說明
keyAPI Key申請(qǐng)的唯一標(biāo)識(shí)
address地址結(jié)構(gòu)化地址信息
city城市指定查詢城市,可選中文、拼音、citycode或adcode
output輸出格式可選json或xml,默認(rèn)json

Python代碼示例

python

import requests
import json

def geocode(address, city=None, api_key='your_api_key'):
    url = 'https://restapi.amap.com/v3/geocode/geo'
    params = {
        'key': api_key,
        'address': address,
        'output': 'json'
    }
    if city:
        params['city'] = city
        
    response = requests.get(url, params=params)
    data = response.json()
    
    if data['status'] == '1' and int(data['count']) > 0:
        location = data['geocodes'][0]['location']
        longitude, latitude = location.split(',')
        return longitude, latitude
    else:
        return None, None

# 使用示例
api_key = '你的API Key'
address = '北京市朝陽區(qū)阜通東大街6號(hào)'
lng, lat = geocode(address, api_key=api_key)
print(f'經(jīng)緯度:經(jīng)度={lng}, 緯度={lat}')

返回結(jié)果示例

json

{
  "status": "1",
  "info": "OK",
  "infocode": "10000",
  "count": "1",
  "geocodes": [
    {
      "formatted_address": "北京市朝陽區(qū)阜通東大街6號(hào)",
      "country": "中國",
      "province": "北京市",
      "citycode": "010",
      "city": "北京市",
      "district": "朝陽區(qū)",
      "township": [],
      "neighborhood": {"name": [], "type": []},
      "building": {"name": [], "type": []},
      "adcode": "110105",
      "street": "阜通東大街",
      "number": "6號(hào)",
      "location": "116.480881,39.989410",
      "level": "門牌號(hào)"
    }
  ]
}

3.2 逆地理編碼

逆地理編碼是將經(jīng)緯度坐標(biāo)轉(zhuǎn)換為結(jié)構(gòu)化地址的過程13。

API地址https://restapi.amap.com/v3/geocode/regeo

請(qǐng)求參數(shù)

參數(shù)名含義是否必須說明
keyAPI Key申請(qǐng)的唯一標(biāo)識(shí)
location經(jīng)緯度格式為"經(jīng)度,緯度"
radius搜索半徑單位:米,取值范圍0-3000,默認(rèn)1000
extensions返回結(jié)果擴(kuò)展可選base或all,默認(rèn)base
poitypePOI類型逆地理編碼時(shí)返回的POI類型
roadlevel道路等級(jí)可選0或1,需extensions=all時(shí)生效

Python代碼示例

python

def regeocode(location, api_key='your_api_key', extensions='base'):
    url = 'https://restapi.amap.com/v3/geocode/regeo'
    params = {
        'key': api_key,
        'location': location,
        'extensions': extensions,
        'output': 'json'
    }
    
    response = requests.get(url, params=params)
    data = response.json()
    
    if data['status'] == '1':
        return data['regeocode']
    else:
        return None

# 使用示例
location = '116.480881,39.989410'
address_component = regeocode(location, api_key=api_key)
print(address_component)

3.3 路徑規(guī)劃

高德地圖提供了多種路徑規(guī)劃API,包括駕車、步行、騎行等13。以下以駕車路徑規(guī)劃為例。

API地址https://restapi.amap.com/v3/direction/driving

請(qǐng)求參數(shù)

參數(shù)名含義是否必須說明
keyAPI Key申請(qǐng)的唯一標(biāo)識(shí)
origin起點(diǎn)格式為"經(jīng)度,緯度"
destination終點(diǎn)格式為"經(jīng)度,緯度"
strategy策略選擇0-速度最快,1-費(fèi)用最低,2-距離最短,3-不走高速,4-避免擁堵,5-多策略
waypoints途經(jīng)點(diǎn)格式為"經(jīng)度,緯度;經(jīng)度,緯度;..."

Python代碼示例

python

def driving_route(origin, destination, api_key='your_api_key', strategy=0):
    url = 'https://restapi.amap.com/v3/direction/driving'
    params = {
        'key': api_key,
        'origin': origin,
        'destination': destination,
        'strategy': strategy,
        'output': 'json'
    }
    
    response = requests.get(url, params=params)
    data = response.json()
    
    if data['status'] == '1':
        route = data['route']
        path = route['paths'][0]
        distance = path['distance']  # 總距離,米
        duration = path['duration']  # 總時(shí)間,秒
        steps = path['steps']  # 步驟列表
        return distance, duration, steps
    else:
        return None, None, None

# 使用示例
origin = '116.481028,39.989643'
destination = '116.434446,39.90816'
distance, duration, steps = driving_route(origin, destination, api_key=api_key)
print(f'距離:{distance}米,時(shí)間:{duration}秒')

3.4 周邊搜索

周邊搜索用于查找指定位置周圍的興趣點(diǎn)(POI)37。

API地址https://restapi.amap.com/v3/place/around

請(qǐng)求參數(shù)

參數(shù)名含義是否必須說明
keyAPI Key申請(qǐng)的唯一標(biāo)識(shí)
location中心點(diǎn)格式為"經(jīng)度,緯度"
keywords關(guān)鍵字多個(gè)關(guān)鍵字用"|"分隔
types類型POI類型代碼,多個(gè)類型用"|"分隔
radius搜索半徑單位:米,最大值30000,默認(rèn)3000
offset每頁記錄數(shù)每頁記錄數(shù),最大值25,默認(rèn)20
page頁碼當(dāng)前頁碼,默認(rèn)1

Python代碼示例

python

def search_around(location, keywords=None, types=None, radius=3000, api_key='your_api_key'):
    url = 'https://restapi.amap.com/v3/place/around'
    params = {
        'key': api_key,
        'location': location,
        'radius': radius,
        'output': 'json'
    }
    
    if keywords:
        params['keywords'] = keywords
    if types:
        params['types'] = types
        
    response = requests.get(url, params=params)
    data = response.json()
    
    if data['status'] == '1':
        return data['pois']
    else:
        return []

# 使用示例
location = '116.480881,39.989410'
pois = search_around(location, keywords='餐館', api_key=api_key)
for poi in pois:
    print(f"名稱:{poi['name']},地址:{poi['address']},距離:{poi['distance']}米")

4 前端JavaScript地圖顯示

在處理完地理數(shù)據(jù)后,我們需要在前端網(wǎng)頁中顯示地圖和結(jié)果。高德地圖JavaScript API提供了豐富的地圖顯示和交互功能24。

4.1 引入高德地圖JavaScript API

在HTML文件中引入高德地圖JavaScript API:

html

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>高德地圖示例</title>
    <style>
        #map-container {
            width: 100%;
            height: 500px;
        }
    </style>
</head>
<body>
    <div id="map-container"></div>
    
    <script src="https://webapi.amap.com/maps?v=2.0&key=你的JSAPI_KEY"></script>
    <script>
        // 地圖初始化代碼將在這里編寫
    </script>
</body>
</html>

4.2 初始化地圖

使用JavaScript初始化地圖:

javascript

// 初始化地圖
var map = new AMap.Map('map-container', {
    zoom: 13, // 縮放級(jí)別
    center: [116.397428, 39.90923], // 中心點(diǎn)坐標(biāo)
    viewMode: '2D' // 使用2D視圖
});

// 添加控件
map.addControl(new AMap.Scale()); // 比例尺
map.addControl(new AMap.ToolBar()); // 工具欄

4.3 添加點(diǎn)標(biāo)記

在地圖上添加點(diǎn)標(biāo)記4:

javascript

// 添加點(diǎn)標(biāo)記
function addMarker(lnglat, title, content) {
    var marker = new AMap.Marker({
        position: lnglat,
        title: title,
        map: map
    });
    
    // 添加信息窗口
    var infoWindow = new AMap.InfoWindow({
        content: content,
        offset: new AMap.Pixel(0, -30)
    });
    
    // 點(diǎn)擊標(biāo)記顯示信息窗口
    marker.on('click', function() {
        infoWindow.open(map, marker.getPosition());
    });
    
    return marker;
}

// 使用示例
var marker = addMarker([116.480881, 39.989410], '標(biāo)記標(biāo)題', '標(biāo)記內(nèi)容');

4.4 繪制折線和多邊形

在地圖上繪制折線和多邊形4:

javascript

// 繪制折線
function addPolyline(path, strokeColor, strokeWeight) {
    var polyline = new AMap.Polyline({
        path: path,
        strokeColor: strokeColor,
        strokeWeight: strokeWeight,
        map: map
    });
    
    return polyline;
}

// 繪制多邊形
function addPolygon(path, strokeColor, fillColor) {
    var polygon = new AMap.Polygon({
        path: path,
        strokeColor: strokeColor,
        fillColor: fillColor,
        map: map
    });
    
    return polygon;
}

// 使用示例
var path = [
    [116.368904, 39.913423],
    [116.382122, 39.901176],
    [116.387271, 39.912501],
    [116.398258, 39.904600]
];
var polyline = addPolyline(path, "#3366FF", 5);

4.5 地理編碼與逆地理編碼

JavaScript API也提供了地理編碼和逆地理編碼的功能10:

javascript

// 地理編碼
function geocode(address, city) {
    return new Promise(function(resolve, reject) {
        AMap.plugin('AMap.Geocoder', function() {
            var geocoder = new AMap.Geocoder({
                city: city || '' // 城市,默認(rèn)全國
            });
            
            geocoder.getLocation(address, function(status, result) {
                if (status === 'complete' && result.geocodes.length > 0) {
                    resolve(result.geocodes[0]);
                } else {
                    reject(status);
                }
            });
        });
    });
}

// 逆地理編碼
function regeocode(lnglat) {
    return new Promise(function(resolve, reject) {
        AMap.plugin('AMap.Geocoder', function() {
            var geocoder = new AMap.Geocoder();
            
            geocoder.getAddress(lnglat, function(status, result) {
                if (status === 'complete' && result.regeocode) {
                    resolve(result.regeocode);
                } else {
                    reject(status);
                }
            });
        });
    });
}

// 使用示例
geocode('北京市朝陽區(qū)阜通東大街6號(hào)').then(function(result) {
    console.log('地理編碼結(jié)果:', result);
});

regeocode([116.480881, 39.989410]).then(function(result) {
    console.log('逆地理編碼結(jié)果:', result);
});

5 前后端數(shù)據(jù)交互

在實(shí)際應(yīng)用中,通常由Python后端處理數(shù)據(jù),然后將結(jié)果傳遞給前端JavaScript顯示。以下是一種常見的實(shí)現(xiàn)方式。

5.1 Python后端(Flask示例)

使用Flask框架創(chuàng)建后端服務(wù):

python

from flask import Flask, jsonify, request, render_template
import requests

app = Flask(__name__)

# 高德API配置
AMAP_API_KEY = '你的Web服務(wù)API Key'

@app.route('/')
def index():
    return render_template('map.html')

@app.route('/geocode')
def geocode():
    address = request.args.get('address')
    city = request.args.get('city', '')
    
    url = 'https://restapi.amap.com/v3/geocode/geo'
    params = {
        'key': AMAP_API_KEY,
        'address': address,
        'city': city,
        'output': 'json'
    }
    
    response = requests.get(url, params=params)
    data = response.json()
    
    if data['status'] == '1' and int(data['count']) > 0:
        location = data['geocodes'][0]['location']
        lng, lat = location.split(',')
        return jsonify({
            'status': 'success',
            'lng': float(lng),
            'lat': float(lat),
            'address': data['geocodes'][0]['formatted_address']
        })
    else:
        return jsonify({
            'status': 'error',
            'message': '地理編碼失敗'
        })

@app.route('/search_around')
def search_around():
    lng = request.args.get('lng')
    lat = request.args.get('lat')
    keywords = request.args.get('keywords', '')
    radius = request.args.get('radius', 3000, type=int)
    
    url = 'https://restapi.amap.com/v3/place/around'
    params = {
        'key': AMAP_API_KEY,
        'location': f'{lng},{lat}',
        'keywords': keywords,
        'radius': radius,
        'output': 'json'
    }
    
    response = requests.get(url, params=params)
    data = response.json()
    
    if data['status'] == '1':
        return jsonify({
            'status': 'success',
            'pois': data['pois']
        })
    else:
        return jsonify({
            'status': 'error',
            'message': '周邊搜索失敗'
        })

if __name__ == '__main__':
    app.run(debug=True)

5.2 前端與后端交互

前端JavaScript通過Ajax調(diào)用后端API獲取數(shù)據(jù):

javascript

// 獲取地理編碼
function getGeocode(address, city) {
    return fetch(`/geocode?address=${encodeURIComponent(address)}&city=${encodeURIComponent(city)}`)
        .then(response => response.json());
}

// 獲取周邊搜索結(jié)果
function getAroundSearch(lng, lat, keywords, radius) {
    return fetch(`/search_around?lng=${lng}&lat=${lat}&keywords=${encodeURIComponent(keywords)}&radius=${radius}`)
        .then(response => response.json());
}

// 使用示例
getGeocode('北京市朝陽區(qū)阜通東大街6號(hào)').then(data => {
    if (data.status === 'success') {
        console.log('經(jīng)緯度:', data.lng, data.lat);
        // 在地圖上添加標(biāo)記
        addMarker([data.lng, data.lat], data.address, data.address);
        // 設(shè)置地圖中心點(diǎn)
        map.setCenter([data.lng, data.lat]);
    }
});

// 搜索周邊并顯示結(jié)果
function searchAndShow(lng, lat, keywords) {
    getAroundSearch(lng, lat, keywords, 1000).then(data => {
        if (data.status === 'success') {
            data.pois.forEach(poi => {
                var location = poi.location.split(',');
                var lnglat = [parseFloat(location[0]), parseFloat(location[1])];
                
                addMarker(lnglat, poi.name, `
                    <div>
                        <h3>${poi.name}</h3>
                        <p>地址:${poi.address}</p>
                        <p>類型:${poi.type}</p>
                        <p>距離:${poi.distance}米</p>
                    </div>
                `);
            });
        }
    });
}

5.3 完整示例:地址查詢與周邊搜索

以下是一個(gè)完整的示例,實(shí)現(xiàn)地址查詢和周邊搜索功能:

html

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>地圖查詢示例</title>
    <style>
        #map-container {
            width: 100%;
            height: 500px;
        }
        .controls {
            margin: 10px 0;
            padding: 10px;
            background: #f5f5f5;
            border-radius: 5px;
        }
        input, button {
            padding: 8px;
            margin: 5px;
        }
    </style>
</head>
<body>
    <div class="controls">
        <input type="text" id="address-input" placeholder="輸入地址">
        <input type="text" id="city-input" placeholder="輸入城市(可選)">
        <button id="geocode-btn">查詢地址</button>
        <input type="text" id="keywords-input" placeholder="搜索關(guān)鍵詞">
        <button id="search-btn">周邊搜索</button>
    </div>
    <div id="map-container"></div>
    
    <script src="https://webapi.amap.com/maps?v=2.0&key=你的JSAPI_KEY"></script>
    <script>
        // 初始化地圖
        var map = new AMap.Map('map-container', {
            zoom: 13,
            center: [116.397428, 39.90923],
            viewMode: '2D'
        });
        
        // 添加控件
        map.addControl(new AMap.Scale());
        map.addControl(new AMap.ToolBar());
        
        // 存儲(chǔ)當(dāng)前中心點(diǎn)標(biāo)記
        var centerMarker = null;
        
        // 地理編碼查詢
        document.getElementById('geocode-btn').addEventListener('click', function() {
            var address = document.getElementById('address-input').value;
            var city = document.getElementById('city-input').value;
            
            if (!address) {
                alert('請(qǐng)輸入地址');
                return;
            }
            
            getGeocode(address, city).then(data => {
                if (data.status === 'success') {
                    // 移除原有標(biāo)記
                    if (centerMarker) {
                        map.remove(centerMarker);
                    }
                    
                    // 添加新標(biāo)記
                    centerMarker = addMarker([data.lng, data.lat], data.address, data.address);
                    
                    // 設(shè)置地圖中心
                    map.setCenter([data.lng, data.lat]);
                    
                    alert('查詢成功:' + data.address);
                } else {
                    alert('查詢失?。? + data.message);
                }
            });
        });
        
        // 周邊搜索
        document.getElementById('search-btn').addEventListener('click', function() {
            var center = map.getCenter();
            var keywords = document.getElementById('keywords-input').value;
            
            if (!keywords) {
                alert('請(qǐng)輸入搜索關(guān)鍵詞');
                return;
            }
            
            searchAndShow(center.lng, center.lat, keywords);
        });
        
        // 添加標(biāo)記函數(shù)
        function addMarker(lnglat, title, content) {
            var marker = new AMap.Marker({
                position: lnglat,
                title: title,
                map: map
            });
            
            var infoWindow = new AMap.InfoWindow({
                content: content,
                offset: new AMap.Pixel(0, -30)
            });
            
            marker.on('click', function() {
                infoWindow.open(map, marker.getPosition());
            });
            
            return marker;
        }
        
        // 獲取地理編碼
        function getGeocode(address, city) {
            return fetch(`/geocode?address=${encodeURIComponent(address)}&city=${encodeURIComponent(city)}`)
                .then(response => response.json());
        }
        
        // 周邊搜索并顯示結(jié)果
        function searchAndShow(lng, lat, keywords) {
            // 先清除之前的搜索結(jié)果
            clearSearchResults();
            
            getAroundSearch(lng, lat, keywords, 1000).then(data => {
                if (data.status === 'success') {
                    data.pois.forEach(poi => {
                        var location = poi.location.split(',');
                        var lnglat = [parseFloat(location[0]), parseFloat(location[1])];
                        
                        addMarker(lnglat, poi.name, `
                            <div>
                                <h3>${poi.name}</h3>
                                <p>地址:${poi.address}</p>
                                <p>類型:${poi.type}</p>
                                <p>距離:${poi.distance}米</p>
                            </div>
                        `);
                    });
                    
                    alert('找到 ' + data.pois.length + ' 個(gè)結(jié)果');
                } else {
                    alert('搜索失敗:' + data.message);
                }
            });
        }
        
        // 獲取周邊搜索結(jié)果
        function getAroundSearch(lng, lat, keywords, radius) {
            return fetch(`/search_around?lng=${lng}&lat=${lat}&keywords=${encodeURIComponent(keywords)}&radius=${radius}`)
                .then(response => response.json());
        }
        
        // 清除搜索結(jié)果
        function clearSearchResults() {
            // 在實(shí)際應(yīng)用中,需要記錄所有搜索結(jié)果的標(biāo)記并移除
            // 這里簡化處理,只移除不是中心點(diǎn)的標(biāo)記
            if (centerMarker) {
                map.remove(centerMarker);
                centerMarker = null;
            }
            // 更完整的實(shí)現(xiàn)需要維護(hù)一個(gè)標(biāo)記列表
        }
    </script>
</body>
</html>

6 高級(jí)功能與優(yōu)化

6.1 使用WebSocket實(shí)時(shí)更新位置

對(duì)于需要實(shí)時(shí)更新位置的場景,可以使用WebSocket實(shí)現(xiàn):

python

// 連接WebSocket
var socket = io();

// 發(fā)送位置更新
function updateLocation(lng, lat) {
    socket.emit('update_location', {
        lng: lng,
        lat: lat,
        timestamp: Date.now()
    });
}

// 接收位置更新
socket.on('location_updated', function(data) {
    // 更新地圖上的位置標(biāo)記
    updateMarker(data);
});

前端代碼:

javascript

// 連接WebSocket
var socket = io();

// 發(fā)送位置更新
function updateLocation(lng, lat) {
    socket.emit('update_location', {
        lng: lng,
        lat: lat,
        timestamp: Date.now()
    });
}

// 接收位置更新
socket.on('location_updated', function(data) {
    // 更新地圖上的位置標(biāo)記
    updateMarker(data);
});

6.2 使用數(shù)據(jù)庫存儲(chǔ)位置數(shù)據(jù)

通常需要將位置數(shù)據(jù)存儲(chǔ)到數(shù)據(jù)庫中,以下是一個(gè)使用SQLite的示例:

python

import sqlite3
from datetime import datetime

def init_db():
    conn = sqlite3.connect('locations.db')
    c = conn.cursor()
    c.execute('''
        CREATE TABLE IF NOT EXISTS locations
        (id INTEGER PRIMARY KEY AUTOINCREMENT,
         lng REAL NOT NULL,
         lat REAL NOT NULL,
         address TEXT,
         created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)
    ''')
    conn.commit()
    conn.close()

def save_location(lng, lat, address=None):
    conn = sqlite3.connect('locations.db')
    c = conn.cursor()
    c.execute('''
        INSERT INTO locations (lng, lat, address)
        VALUES (?, ?, ?)
    ''', (lng, lat, address))
    conn.commit()
    conn.close()

def get_locations(limit=100):
    conn = sqlite3.connect('locations.db')
    c = conn.cursor()
    c.execute('''
        SELECT lng, lat, address, created_at
        FROM locations
        ORDER BY created_at DESC
        LIMIT ?
    ''', (limit,))
    results = c.fetchall()
    conn.close()
    return results

6.3 性能優(yōu)化建議

  1. 使用緩存:對(duì)于頻繁查詢的地址,可以使用緩存減少API調(diào)用7。

  2. 批量處理:當(dāng)需要處理大量地址時(shí),可以考慮使用批量查詢功能(如果API支持)。

  3. 錯(cuò)誤處理:添加適當(dāng)?shù)腻e(cuò)誤處理和重試機(jī)制7。

  4. 速率限制:遵守高德地圖API的調(diào)用頻率限制7。

7 總結(jié)

本文詳細(xì)介紹了如何使用Python開發(fā)調(diào)用高德地圖API,并在JavaScript網(wǎng)頁中顯示地圖。主要內(nèi)容包括:

  1. 高德地圖API的申請(qǐng)和使用:包括Web服務(wù)API和JavaScript API。

  2. Python調(diào)用高德Web服務(wù)API:實(shí)現(xiàn)地理編碼、逆地理編碼、路徑規(guī)劃和周邊搜索等功能。

  3. 前端JavaScript地圖顯示:初始化地圖、添加標(biāo)記、繪制圖形等。

  4. 前后端數(shù)據(jù)交互:使用Flask框架搭建后端服務(wù),前端通過Ajax調(diào)用后端API。

  5. 高級(jí)功能與優(yōu)化:使用WebSocket實(shí)時(shí)更新位置、數(shù)據(jù)庫存儲(chǔ)和性能優(yōu)化。

通過本文的學(xué)習(xí),你可以實(shí)現(xiàn)一個(gè)完整的地圖應(yīng)用,包括地址查詢、位置顯示、周邊搜索等功能。在實(shí)際開發(fā)中,可以根據(jù)需求進(jìn)一步擴(kuò)展功能,如路徑規(guī)劃、地理圍欄、實(shí)時(shí)定位等。

7.1 進(jìn)一步學(xué)習(xí)資源

  1. 高德地圖官方文檔

  2. Flask官方文檔

  3. JavaScript異步編程

到此這篇關(guān)于Python調(diào)用高德地圖API實(shí)現(xiàn)JS網(wǎng)頁地圖顯示的文章就介紹到這了,更多相關(guān)Python調(diào)用高德地圖API實(shí)現(xiàn)JS網(wǎng)頁地圖顯示內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 一文詳解如何使用Python批量拼接圖片

    一文詳解如何使用Python批量拼接圖片

    這篇文章主要給大家介紹了關(guān)于如何使用Python批量拼接圖片的相關(guān)資料,文中主要用的是PIL庫,PIL庫是一個(gè)具有強(qiáng)大圖像處理能力的第三方庫,不僅包含了豐富的像素、色彩操作功能,還可以用于圖像歸檔和批量處理,需要的朋友可以參考下
    2023-05-05
  • 10個(gè)簡單但很有用的Python裝飾器分享

    10個(gè)簡單但很有用的Python裝飾器分享

    裝飾器(Decorators)是Python中一種強(qiáng)大而靈活的功能,用于修改或增強(qiáng)函數(shù)或類的行為,本文為大家整理了10個(gè)簡單但很有用的Python裝飾器,希望對(duì)大家有所幫助
    2023-08-08
  • python中__slots__節(jié)約內(nèi)存的具體做法

    python中__slots__節(jié)約內(nèi)存的具體做法

    在本篇內(nèi)容里小編給大家分享的是一篇關(guān)于python中__slots__節(jié)約內(nèi)存的具體做法,有需要的朋友們可以跟著學(xué)習(xí)參考下。
    2021-07-07
  • python中subprocess實(shí)例用法及知識(shí)點(diǎn)詳解

    python中subprocess實(shí)例用法及知識(shí)點(diǎn)詳解

    在本篇文章里小編給大家分享的是關(guān)于python中subprocess實(shí)例用法及知識(shí)點(diǎn)詳解內(nèi)容,有需要的朋友們可以跟著學(xué)習(xí)下。
    2021-10-10
  • Python3 JSON編碼解碼方法詳解

    Python3 JSON編碼解碼方法詳解

    這篇文章主要介紹了Python3 JSON編碼解碼方法詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-09-09
  • Python數(shù)據(jù)解析bs4庫使用BeautifulSoup方法示例

    Python數(shù)據(jù)解析bs4庫使用BeautifulSoup方法示例

    這篇文章主要為大家介紹了Python數(shù)據(jù)解析bs4庫使用BeautifulSoup方法示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-08-08
  • Pandas DataFrame分組求和、分組乘積的實(shí)例

    Pandas DataFrame分組求和、分組乘積的實(shí)例

    這篇文章主要介紹了Pandas DataFrame分組求和、分組乘積的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-02-02
  • PyTorch搭建一維線性回歸模型(二)

    PyTorch搭建一維線性回歸模型(二)

    這篇文章主要為大家詳細(xì)介紹了PyTorch搭建一維線性回歸模型,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2019-05-05
  • python3.7調(diào)試的實(shí)例方法

    python3.7調(diào)試的實(shí)例方法

    在本篇文章里小編給大家整理的是一篇關(guān)于python3.7調(diào)試的實(shí)例方法,需要的朋友可以學(xué)習(xí)下。
    2020-07-07
  • Pytest框架之fixture詳解(三)

    Pytest框架之fixture詳解(三)

    本文詳細(xì)講解了Pytest框架之fixture,文中通過示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-06-06

最新評(píng)論