使用html2canvas,Google地图屏幕截图不适用于标记和标记群集 [英] Google Map screen capture is not working for marker and marker cluster using html2canvas
问题描述
我正在使用烧瓶进行python项目,我使用google map api在项目中显示地图。我使用 html2canvas 脚本成功捕获地图。但是我在地图上也没有捕捉到标记。所以我尝试使用 html2canvasPythonProxy
这是我的模板JavaScript文件的片段gpsDataMap:
$(window).load(function(){
$('#saveMap')。click (函数(){
html2canvas(document.getElementById('map'),{
logging:true,//启用日志(使用Web控制台获取错误和警告)
proxy:/ surveyApp / gpsDataMap / html2canvas-proxy,
useCORS:true,
onrendered:function(canvas){
var img = new Image();
img.onload = function(){
img.onload = null;
document.body.appendChild(img);
};
img.onerror = function(){
img.onerror = null;
if(window.console.log){
window.console.log(未加载canvas.t中的图片oDataURL);
} else {
alert(未从canvas.toDataURL加载图片);
}
};
img.src = canvas.toDataURL(image / png);
}
});
});
});
以及我的代码片段:
导入os
导入日期时间
从flask导入烧瓶,请求,render_template,重定向,url_for,flash,响应$ b $ from flask.json导入转储
从瓶子导入json
从瓶子导入g,Blueprint,session,abort $ b $ from flask_principal import标识,identity_changed,identity_loaded,RoleNeed,AnonymousIdentity $ b $ from flask_login import LoginManager,login_user ,login_required,logout_user $ b $从应用程序导入应用程序
从model.user_info导入SurveyForms
$ b从flask.ext.pymongo导入PyMongo
从inspect导入getmembers ,isfunction
导入formConfig
导入formTree
导入fieldChoices
从仪表板导入dashboardData
从集合导入namedtuple
从pymongo导入MongoClient
从瓶子导入请求
from html2canvasproxy import * #include html2canvasproxy in your appl ication
import urlparse
import re
$ b surveyApp_module = Blueprint('surveyApp_module',__name__)
app.config ['MONGO_HOST'] ='localhost'
app.config ['MONGO_PORT'] = 27017
app.config ['MONGO_DBNAME'] ='survey'
mongo = PyMongo(app)
h2c = None
real_path = os.getcwd()+'/ static / images'
virtual_path ='/ gpsDataMap / images /'
@ surveyApp_module.route('/')
@login_required
def show_formList():
forms = []
forms = [form.form_name for在SurveyForms.select()中创建表单。其中(SurveyForms.organization_name ==会议['organization_id'])]
#字符串.xml从字符串与returnData
forms = [form.replace('。
returnData = mongo.db.collection_names()
returnData.pop(returnData.index('system.indexes'))
intersected_forms = list (集(形式).intersection(returnData) )
len(intersected_forms):
return render_template('index_pjj.html',surveyEntries = intersected_forms)
return render_template('index_pjj.html',surveyEntries = ['No Survey'])
@ surveyApp_module.route('/ dashboard',methods = ['POST'])
def dashboard():
formName = request.form ['whichSurvey']
session ['formName'] = formName
formtree = formTree.formParseDict(formName)
returnData = dashboardData(formName,mongo.db)
summaryData = totalSummary(formName,mongo.db )
jsonData = json.dumps(returnData)
return render_template('dashboard.html',formName = formName,formTree = formtree,returnData = returnData,summaryData = summaryData,jsonData = jsonData)
@ surveyApp_module.route('/ gpsDataView',methods = ['POST'])
def gpsDataView():
formName = request.form ['whichSurvey']
gpsFields = formConfig.survey [formName] ['gpsField']
(location,fieldName,fieldSelection,fieldChoicesList)=,,,[]
location = request.form ['location']
fieldName = request.form ['' fieldName']
try:
fieldSelection = request.form ['fieldChoices']
除了KeyError:
传递
fieldChoicesList = request.form.getlist('fieldChoicesList' )
fieldData = commonFunctions.vizFieldList(formName)
totalFieldData = commonFunctions.vizFieldListFull(formName)
locationIdentifiers = fieldChoices.locationFieldChoices(formName,mongo.db)
returnData = gpsVariate.getDataforGPSMap (formName,mongo.db,gpsFields,location,fieldName,fieldSelection,fieldChoicesList)
return render_template('gpsDataMap.html',returnData = returnData,formName = formName,fieldData = fieldData,totalFieldData = totalFieldData,locationIdentifiers = locationIdentifiers)
#复制html2canvas.js到静态文件夹(如果不使用cdns)
@ surveyApp_module.route('/ gpsDataMap / html2canvas.js')
def html2canvas_js():
返回app.send_static_file('html2canvas.js')
surveyApp_module.route('/ gpsDataMap / html2canvas-proxy')
def html2canvas_proxy():
print(这个代理真的在调用);
h2c = html2canvasproxy(request.args.get('callback'),request.args.get('url'))
h2c.userAgent(request.headers ['user_agent'])
#import pdb; pdb.set_trace()
$ b $如果request.referrer不是无:
h2c.referer(request.referrer)
h2c.route(real_path,virtual_path)
r = h2c.result()
#print r ['mime']
#print r ['data']
返回响应(r ['data'],mimetype = r ['mime'])
#获取由html2canvasproxy保存的图像
@ surveyApp_module.route('/ gpsDataMap / html2canvas / images /< image>)
def images(image):
res = html2canvasproxy.resource(real_path,image)
如果res为None:
return'',404
else:
return res ['data']
以下是我的main.py脚本:
从应用导入应用中,db
从auth导入*
from admin import admin
从模型导入*
从视图导入*
从filters.user_privilege导入check_privilege
从filters.form_filter导入filter_type
#自定义过滤器
app.jinja_env.filters ['check_privilege'] = check_privilege
app.jinja_env.filters ['filter_type'] =过滤器类型
from surveyApp导入surveyApp_module
app.register_blueprint(surveyApp_module,url_prefix ='/ surveyApp')
from view.accounts.login import login_module
app.register_blueprint(login_module)
if __name__ =='__main__':
app.run(port = 5555)
在这样做的过程中,我在控制台中获得以下内容:
html2canvas:预加载开始:查找背景图片html2canvas.js:21
html2canvas:预加载:查找图片html2canvas.js:21
html2canvas:预加载:完成。 html2canvas.js:21
html2canvas:start:images:1/23(失败:0)html2canvas.js:21
html2canvas:start:images:2/23(失败:0)html2canvas.js: 21
html2canvas:start:images:3/23(失败:0)html2canvas.js:21
html2canvas:start:images:4/23(失败:0)html2canvas.js:21
html2canvas:start:images:5/23(失败:0)html2canvas.js:21
html2canvas:start:images:6/23(失败:0)html2canvas.js:21
html2canvas:start :images:7/23(失败:0)html2canvas.js:21
html2canvas:start:images:8/23(失败:0)html2canvas.js:21
html2canvas:start:images:9 / 23(失败:0)html2canvas.js:21
html2canvas:start:images:10/23(失败:0)html2canvas.js:21
html2canvas:start:images:11/23 :0)html2canvas.js:21
html2canvas:start:images:12/23(失败:0)html2canvas.js:21
html2canvas:start:images:13/23(失败:0)html2canvas .js:21
html2canvas:start:images:14/23(失败:0)html2canvas.js: 21
html2canvas:start:images:15/23(失败:0)html2canvas.js:21
html2canvas:start:images:16/23(失败:0)html2canvas.js:21
html2canvas:start:images:17/23(失败:0)html2canvas.js:21
html2canvas:start:images:18/23(失败:0)html2canvas.js:21
html2canvas:start :images:19/23(失败:0)html2canvas.js:21
html2canvas:start:images:20/23(失败:0)html2canvas.js:21
html2canvas:start:images:21 / 23(失败:0)html2canvas.js:21
html2canvas:start:images:22/23(失败:0)html2canvas.js:21
GET http://127.0.0.1:5555/ home / bhim / app / surveyApp_bhim / images / a0af53c02bd2f2aed37f1d895edcf3485117c512.png html2canvas.js:2249
html2canvas:start:images:23/23(失败:1)html2canvas.js:21
完成加载图片:#23(失败:1)html2canvas.js:21
html2canvas:加载背景错误:html2canvas.js:21
html2canvas:渲染器:Canvas渲染器完成 - 返回canvas obj
$ C $
UPDATED :
调试器结果:
folder =>图像,
timeout => 30,
mimetype => application / javascript,
ua => Mozilla / 5.0(X11; Ubuntu; Linux x86_64; rv:29.0)Gecko / 20100101 Firefox / 29.0,
host => 127.0.0.1:5555,
scheme => http,
ref => ,
url => http://www.google.com,
callback => console.log,
default_callback => console.log,
status => 0,
routePath => / static / images /,
savePath => / home / bhim / app / surveyApp_bhim / static / images /,
prefix => htc_,
real_extension => ,
mimes => ['image / bmp','image / windows-bmp','image / ms-bmp','image / jpeg','image / jpg','image / png','image / gif','text / html','application / xhtml','application / xhtml + xml']
UPDATED Google地图图片的屏幕截图
$ b
标记不被捕获。解决方案<1>使用
useCORS:true
或使用代理
,不要同时使用两者。 您的路线不同,请参阅
virtual_path ='/ gpsDataMap / images /'
@ surveyApp_module.route('/ gpsDataMap / html2canvas / images /< image>)
<3>您的代理r oute,似乎是错误的(在你的Javascript中):
$ b
proxy:/ surveyApp / gpsDataMap / html2canvas-proxy,
@ surveyApp_module.route('/ gpsDataMap / html2canvas-代理')
没有意识到所有错误,为什么带有PROXY的
userCORS
会感到困惑。
修复所有路线他们的虚拟路径)并修复了你的javascript(不要使用
userCORS:
),见:
$(window).load(function(){
$('#saveMap')。click(function(){
html2canvas(document.getElementById('map'), {
logging:true,//启用日志(使用Web控制台获取错误和警告)
// useCORS:true,COMMENTED,remove useCORS
proxy:YOUR_FIXED_ROUTE ,
onrendered:function(canvas){
var img = new Image();
img.onload = function(){
img.onload = null;
document.body.appendChild(img);
};
img.onerror = function(){
img.onerror = null;
if(window.console.log){
window.console.log(未从canvas.toDataURL加载图片);
} else {
alert(未从canvas.toDataURL加载图片);
}
};
img.src = canvas.toDataURL(image / png);
}
});
});
});
看来,这是绝对路径与路线:
GET http://127.0.0.1:5555/home/bhim/app/surveyApp_bhim/images/a0af53c02bd2f2aed37f1d895edcf3485117c512.png 404(NOT FOUND)html2canvas.js:2249
任何原因的代理响应路径都是错误的,使用这个:
1)编辑您的代码,如下所示:
$ b <2>在浏览器中运行:@ surveyApp_module.route('/ gpsDataMap / html2canvas-proxy')
def html2canvas_proxy():
print(this is really really calling);
h2c = html2canvasproxy(request.args.get('callback'),request.args.get('url'))
h2c.userAgent(request.headers ['user_agent'])
如果request.referrer不是None:
h2c.referer(request.referrer)
$ b $如果request.args.get('debug_vars'):#增加
返回响应((',\ n'.join(h2c.debug_vars())),mimetype ='text / plain')#添加
h2c.route(real_path,virtual_path)
r = h2c.result()
return Response(r ['data'],mimetype = r ['mime'])
http://127.0.0.1:5000 /gpsDataMap/html2canvas-proxy?callback=console.log&url=http://www.google.com&debug_vars=1
3)获得结果并发布在你的queston上。
I am doing python project using flask where I used google map api to show the map in the project. I implement html2canvas script to capture the map successfully. But I have marker too in the map which it is not capturing. So I tried using html2canvasPythonProxy Here is my snippet of javascript file of template gpsDataMap:
$(window).load(function(){ $('#saveMap').click(function(){ html2canvas(document.getElementById('map'), { "logging": true, //Enable log (use Web Console for get Errors and Warnings) "proxy":"/surveyApp/gpsDataMap/html2canvas-proxy", useCORS:true, "onrendered": function(canvas) { var img = new Image(); img.onload = function() { img.onload = null; document.body.appendChild(img); }; img.onerror = function() { img.onerror = null; if(window.console.log) { window.console.log("Not loaded image from canvas.toDataURL"); } else { alert("Not loaded image from canvas.toDataURL"); } }; img.src = canvas.toDataURL("image/png"); } }); }); });
And My snippet of python code:
import os import datetime from flask import Flask, request, render_template, redirect, url_for, flash, Response from flask.json import dumps from flask import json from flask import g, Blueprint, session, abort from flask_principal import Identity, identity_changed, identity_loaded, RoleNeed, AnonymousIdentity from flask_login import LoginManager, login_user, login_required, logout_user from app import app from model.user_info import SurveyForms from flask.ext.pymongo import PyMongo from inspect import getmembers, isfunction import formConfig import formTree import fieldChoices from dashboard import dashboardData from collections import namedtuple from pymongo import MongoClient from flask import request from html2canvasproxy import * #include html2canvasproxy in your application import urlparse import re surveyApp_module = Blueprint('surveyApp_module', __name__) app.config['MONGO_HOST'] = 'localhost' app.config['MONGO_PORT'] = 27017 app.config['MONGO_DBNAME'] = 'survey' mongo = PyMongo(app) h2c = None real_path = os.getcwd() + '/static/images' virtual_path = '/gpsDataMap/images/' @surveyApp_module.route('/') @login_required def show_formList(): forms = [] forms = [form.form_name for form in SurveyForms.select().where(SurveyForms.organization_name==session['organization_id'])] # strip .xml from string to compare with returnData forms = [form.replace('.xml','') for form in forms] returnData = mongo.db.collection_names() returnData.pop(returnData.index('system.indexes')) intersected_forms = list(set(forms).intersection(returnData)) if len(intersected_forms): return render_template('index_pjj.html', surveyEntries=intersected_forms) return render_template('index_pjj.html', surveyEntries=['No Survey']) @surveyApp_module.route('/dashboard', methods=['POST']) def dashboard(): formName = request.form['whichSurvey'] session['formName'] = formName formtree = formTree.formParseDict(formName) returnData = dashboardData(formName, mongo.db) summaryData = totalSummary(formName, mongo.db) jsonData = json.dumps(returnData) return render_template('dashboard.html', formName=formName, formTree=formtree, returnData=returnData, summaryData=summaryData, jsonData=jsonData) @surveyApp_module.route('/gpsDataView', methods=['POST']) def gpsDataView(): formName = request.form['whichSurvey'] gpsFields = formConfig.survey[formName]['gpsField'] (location, fieldName, fieldSelection, fieldChoicesList) = "", "", "", [] location = request.form['location'] fieldName = request.form['fieldName'] try: fieldSelection = request.form['fieldChoices'] except KeyError: pass fieldChoicesList = request.form.getlist('fieldChoicesList') fieldData = commonFunctions.vizFieldList(formName) totalFieldData = commonFunctions.vizFieldListFull(formName) locationIdentifiers = fieldChoices.locationFieldChoices(formName, mongo.db) returnData = gpsVariate.getDataforGPSMap(formName, mongo.db, gpsFields, location, fieldName, fieldSelection, fieldChoicesList) return render_template('gpsDataMap.html', returnData=returnData, formName=formName, fieldData=fieldData, totalFieldData=totalFieldData, locationIdentifiers=locationIdentifiers) #Copy html2canvas.js to static folder (If not use cdns) @surveyApp_module.route('/gpsDataMap/html2canvas.js') def html2canvas_js(): return app.send_static_file('html2canvas.js') @surveyApp_module.route('/gpsDataMap/html2canvas-proxy') def html2canvas_proxy(): print ("is this proxy really calling "); h2c = html2canvasproxy(request.args.get('callback'), request.args.get('url')) h2c.userAgent(request.headers['user_agent']) # import pdb;pdb.set_trace() if request.referrer is not None: h2c.referer(request.referrer) h2c.route(real_path, virtual_path) r = h2c.result() # print r['mime'] # print r['data'] return Response(r['data'], mimetype=r['mime']) # Get images saved by html2canvasproxy @surveyApp_module.route('/gpsDataMap/html2canvas/images/<image>') def images(image): res = html2canvasproxy.resource(real_path, image) if res is None: return '', 404 else: return res['data']
Here is my main.py script:
from app import app, db from auth import * from admin import admin from model import * from view import * from filters.user_privilege import check_privilege from filters.form_filter import filter_type # custom filters app.jinja_env.filters['check_privilege'] = check_privilege app.jinja_env.filters['filter_type'] = filter_type from surveyApp import surveyApp_module app.register_blueprint(surveyApp_module, url_prefix='/surveyApp') from view.accounts.login import login_module app.register_blueprint(login_module) if __name__ == '__main__': app.run(port=5555)
While doing so I get the following things in my console:
html2canvas: Preload starts: finding background-images html2canvas.js:21 html2canvas: Preload: Finding images html2canvas.js:21 html2canvas: Preload: Done. html2canvas.js:21 html2canvas: start: images: 1 / 23 (failed: 0) html2canvas.js:21 html2canvas: start: images: 2 / 23 (failed: 0) html2canvas.js:21 html2canvas: start: images: 3 / 23 (failed: 0) html2canvas.js:21 html2canvas: start: images: 4 / 23 (failed: 0) html2canvas.js:21 html2canvas: start: images: 5 / 23 (failed: 0) html2canvas.js:21 html2canvas: start: images: 6 / 23 (failed: 0) html2canvas.js:21 html2canvas: start: images: 7 / 23 (failed: 0) html2canvas.js:21 html2canvas: start: images: 8 / 23 (failed: 0) html2canvas.js:21 html2canvas: start: images: 9 / 23 (failed: 0) html2canvas.js:21 html2canvas: start: images: 10 / 23 (failed: 0) html2canvas.js:21 html2canvas: start: images: 11 / 23 (failed: 0) html2canvas.js:21 html2canvas: start: images: 12 / 23 (failed: 0) html2canvas.js:21 html2canvas: start: images: 13 / 23 (failed: 0) html2canvas.js:21 html2canvas: start: images: 14 / 23 (failed: 0) html2canvas.js:21 html2canvas: start: images: 15 / 23 (failed: 0) html2canvas.js:21 html2canvas: start: images: 16 / 23 (failed: 0) html2canvas.js:21 html2canvas: start: images: 17 / 23 (failed: 0) html2canvas.js:21 html2canvas: start: images: 18 / 23 (failed: 0) html2canvas.js:21 html2canvas: start: images: 19 / 23 (failed: 0) html2canvas.js:21 html2canvas: start: images: 20 / 23 (failed: 0) html2canvas.js:21 html2canvas: start: images: 21 / 23 (failed: 0) html2canvas.js:21 html2canvas: start: images: 22 / 23 (failed: 0) html2canvas.js:21 GET http://127.0.0.1:5555/home/bhim/app/surveyApp_bhim/images/a0af53c02bd2f2aed37f1d895edcf3485117c512.png 404 (NOT FOUND) html2canvas.js:2249 html2canvas: start: images: 23 / 23 (failed: 1) html2canvas.js:21 Finished loading images: # 23 (failed: 1) html2canvas.js:21 html2canvas: Error loading background: html2canvas.js:21 html2canvas: Renderer: Canvas renderer done - returning canvas obj
UPDATED: The debugger result:
folder => images, timeout => 30, mimetype => application/javascript, ua => Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:29.0) Gecko/20100101 Firefox/29.0, host => 127.0.0.1:5555, scheme => http, ref => , url => http://www.google.com, callback => console.log, default_callback => console.log, status => 0, routePath => /static/images/, savePath => /home/bhim/app/surveyApp_bhim/static/images/, prefix => htc_, real_extension => , mimes => ['image/bmp', 'image/windows-bmp', 'image/ms-bmp', 'image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'text/html', 'application/xhtml', 'application/xhtml+xml']
UPDATED Screenshot of the images of google map
The marker is not being captured.
解决方案1) Use
useCORS:true
or useproxy
, never use both at the same time.2) Your routes are different, see:
virtual_path = '/gpsDataMap/images/'
@surveyApp_module.route('/gpsDataMap/html2canvas/images/<image>')
3) Your proxy route, seems to be wrong (in your Javascript):
"proxy":"/surveyApp/gpsDataMap/html2canvas-proxy",
@surveyApp_module.route('/gpsDataMap/html2canvas-proxy')
You do not realize all errors, why the
userCORS
with the "PROXY" get confused.Fix all routes (routes are their virtual paths) and fix your javascript (don't use
userCORS:
), see:$(window).load(function(){ $('#saveMap').click(function(){ html2canvas(document.getElementById('map'), { "logging": true, //Enable log (use Web Console for get Errors and Warnings) //useCORS:true, "COMMENTED", remove useCORS "proxy": YOUR_FIXED_ROUTE, "onrendered": function(canvas) { var img = new Image(); img.onload = function() { img.onload = null; document.body.appendChild(img); }; img.onerror = function() { img.onerror = null; if(window.console.log) { window.console.log("Not loaded image from canvas.toDataURL"); } else { alert("Not loaded image from canvas.toDataURL"); } }; img.src = canvas.toDataURL("image/png"); } }); }); });
See, this is absolute path mixed with "routes":
GET http://127.0.0.1:5555/home/bhim/app/surveyApp_bhim/images/a0af53c02bd2f2aed37f1d895edcf3485117c512.png 404 (NOT FOUND) html2canvas.js:2249
The route of proxy response for any reason is wrong, use this:
1) Edit your code, like this:
@surveyApp_module.route('/gpsDataMap/html2canvas-proxy') def html2canvas_proxy(): print ("is this proxy really calling "); h2c = html2canvasproxy(request.args.get('callback'), request.args.get('url')) h2c.userAgent(request.headers['user_agent']) if request.referrer is not None: h2c.referer(request.referrer) if request.args.get('debug_vars'): #Added return Response((',\n'.join(h2c.debug_vars())), mimetype='text/plain') #Added h2c.route(real_path, virtual_path) r = h2c.result() return Response(r['data'], mimetype=r['mime'])
2) Run in browser:
http://127.0.0.1:5000/gpsDataMap/html2canvas-proxy?callback=console.log&url=http://www.google.com&debug_vars=1
3) Get results and post in your queston.
这篇关于使用html2canvas,Google地图屏幕截图不适用于标记和标记群集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!