Baskaran Baskaran - 2 months ago 15
Javascript Question

How to pass the datastore value to javascript? i need to get data from the gae datastore and need to pass javascript

am working with GAE using webapp2, python.
Now am working in google map using gae. Successfully done with multiple locations.

This is my JavaScript:
======================
<script type="text/javascript">
var USER_POSITION;
var DESTINATION_MARKER;
var ALL_MARKERS = [];

var coordinateArray = [
{coordinates: new google.maps.LatLng(12.9345494,77.6115174), id: "forum", title: "Forum", address_details: Bengaluru<br/>Karnataka-560095"},
{coordinates: new google.maps.LatLng(12.973584,77.611293), id: "central", title: "Central", address_details: Bengaluru<br/>Karnataka-560001"},
{coordinates: new google.maps.LatLng(12.956534,77.701239), id: "busstop", title: "Marathahalli", address_details: Bengaluru<br/>Karnataka-560037"}
];
</script>


Here am using hardcode values. But i need to pass my datastore values.
How do i pass those datastore values to my javascript.

This is my DBModel:
====================
class MapModel(db.Model):
Lattitude=db.StringProperty()
Landitude=db.StringProperty()
Id=db.StringProperty()
Title=db.StringProperty()
Address=db.StringProperty()


Kindly provide some example code.

My.js:



var mapProperty = new google.maps.Map(document.getElementById("example"), myOptions);

for(var i in coordinateArray ) {
var id = coordinateArray[i]['id'];
var title = coordinateArray[i]['title'];
var position = coordinateArray[i]['coordinates'];
var address_details = coordinateArray[i]['address_details'];

var boxText = [
'<div class="info_box">',
..info details..
'</div>'
].join(" ");

var markerOptions = {
animation: markerAnimation,
position: coordinateArray[i]['coordinates'],
icon: markerImage,
map: mapProperty,
html: boxText,
id: id
};

Answer

You can use webapp2 templates to pass the data to your HTML page.

Python Code:

coordinates = MapModel.all()

template_values = {
    'coordinates': coordinates
}    
path = os.path.join(os.path.dirname(__file__), 'YourFile.html')
self.response.out.write(template.render(path, template_values))

In HTML Page:

<script type="text/javascript">
    var USER_POSITION;
    var DESTINATION_MARKER;
    var ALL_MARKERS = [];

    var coordinateArray = [
        {% for cord in coordinates %}
            {coordinates: new google.maps.LatLng({{cord.Lattitude}},{{cord.Landitude}}), id: "{{cord.id}}", title: "{{cord.title}}", address_details: "{{cord.Address}}"},
        {% endfor %}

    ];
</script>