Friday, 17 March 2017

How to send MySQL data to html(google map api embedded) in Node.js

I am developing web-app using node.js and google map api. I want to send data from MySQL DB to client and draw markers using their coordinates. Let me show what I have written.

app.js(serverside):

app.get('/result/:l_area', function(request, response){
fs.readFile('result.html', 'utf8', function(error, data) {
    client.query('SELECT * FROM Locations WHERE l_area=?', [request.params.l_area], function(error, result){
        response.writeHead(200, {'Context-Type': 'text/html'});
        response.end(data, {data: result});
    });
});});

As you can see, routing has it's param and it decides what data to extract. When I made a similar route page using ejs it was successful. But...

result.html:

function initMap(){
        map = new google.maps.Map(document.getElementById('map'), {
            zoom: 8,
            center: new google.maps.LatLng(xxx,xxx)
        });

        $.each(data, function(key, item){
            var latLng = new google.maps.LatLng(item.latitude, item.longitude);
            var marker = new google.maps.Marker({
                position: latLng,
                map: map,
                title: item.l_name
            });
        });

What I got is just an error message of "Uncaught ReferenceError: data is not defined" from chrome dev tool. How to send data to the HTML page to draw markers? Thanks.



via GM Park

No comments:

Post a Comment