I am writing the following line to the end of an html file as javascript. For some reason after the place variable is written to the file, a new line or some similar character is added. I wouldnt mind this because I won't be looking through the written script, but chrome is telling me its an illegal character.
Code to write to html:
map_html.write(
"geocoder.geocode( { 'address': '" + place + "'}, function(results, status) {\n\
var marker = new google.maps.Marker();\n\
marker.setPosition(results[0].geometry.location);\n\
marker.setMap(map);\n\
bounds.extend(marker.position);\n\
});\n"
)
Output:
geocoder.geocode( { 'address': 'Brooklyn, NY
'}, function(results, status) {
var marker = new google.maps.Marker();
marker.setPosition(results[0].geometry.location);
marker.setMap(map);
bounds.extend(marker.position);
});
Replace your code with:
var geo_json = JSON.stringify({ 'address': place});
map_html.write(
"geocoder.geocode(" + geo_json + ", function(results, status) {\n\
var marker = new google.maps.Marker();\n\
marker.setPosition(results[0].geometry.location);\n\
marker.setMap(map);\n\
bounds.extend(marker.position);\n\
});\n"
)
This will sidestep the issue and will allow you to see what the stringify
ed json would look like. It's generally a bad idea to write your own json. Let javascript generate json, it's good at that.
If that still causes pain, then try var geo_json = JSON.stringify({ 'address': place.trim()});
which will strip whitespace from the ends of the place
string.
If that still causes pain, then try a regex to validate the place
input. Something like [A-Za-z_ ,]+
EDIT
Oh, crap, I mixed up javascript and python here.
import json
geo_json = json.dumps({ 'address': place})
map_html.write(
"geocoder.geocode(" + geo_json + ", function(results, status) {\n\
var marker = new google.maps.Marker();\n\
marker.setPosition(results[0].geometry.location);\n\
marker.setMap(map);\n\
bounds.extend(marker.position);\n\
});\n"
)
How about trying a multiline string?
map_html.write(
"geocoder.geocode( { 'address': " + place + "}, function(results, status) {" + """
var marker = new google.maps.Marker();
marker.setPosition(results[0].geometry.location);
marker.setMap(map);
bounds.extend(marker.position);
});
"""
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.