Jones
Jones

Reputation: 399

Global variable javascript not working appropriately

I am working on a website in which I am trying to incorporate Google maps. The page fetches values from a database using php. It then passes one of the column values to a javascript function which plots it using Google Maps. Now, I want to display the plots of all the values in a single map.

I am attaching the javascript function and the php call. Here is the code:

<script type="text/javascript">

var myOptions;
var map;
var geocoder;
var first_call = 0;

function map_function(addr){
    // Define the addresses we want to map.
    var clubs = addr;
    // Create a new Geocoder
    if (first_call == 0){
        var geocoder = new google.maps.Geocoder();
    }
    // Locate the address using the Geocoder.
    geocoder.geocode( { "address": clubs }, function(results, status) {
        // If the Geocoding was successful
        if (status == google.maps.GeocoderStatus.OK) {
            if (first_call == 0){
                // Create a Google Map at the latitude/longitude returned by the Geocoder.
                // Create Once
                alert("Initializing Map");
                var myOptions = {
                    zoom: 16,
                    center: results[0].geometry.location,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                };
                //Initialise once
                var map = new google.maps.Map(document.getElementById("map"), myOptions);
            }
            // Add a marker at the address.
            alert("Plotting address");
            var marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location
            });
        } else {
                try {
                    console.error("Geocode was not successful for the following reason: " + status);
                } catch(e) {}
            }
    });
    first_call = first_call + 1;
    alert (first_call);
}
</script>
<?php
while($row = mysqli_fetch_array($result)){
    $addr = $row['ADDRESS'];
    echo '<script type="text/javascript">map_function("{$addr}");</script>';
?>

I know that the map along with its options should be initialized only once. So I am keeping a track of the function call using first_call and making sure that the map is initialized only on the first call. Besides, I am declaring the map, options and the geocoder as global variables. Unfortunately, I do not get any output. I am really new to javascript and I dont know where am I going wrong.

Anxiously awaiting a solution.

Upvotes: 0

Views: 996

Answers (2)

Anto Jurković
Anto Jurković

Reputation: 11258

I don't know about php code but your javascript code has several errors.

First of all you define mapOptions, map, and geocoder as global and then redefine each of them locally. So, var in front of variables is deleted in function map_function.

The next one which prevents that map is initialized at all is update of first_call variable. Because geocode() is asynchronous function, first_call is set to 1 and then increased further even before code reach the check if (first_call == 0){. So the map is never initialized.

Below is changed code with my test code without php:

<script type="text/javascript">

var myOptions;
var map;
var geocoder;
var first_call = 0;

function map_function(addr){
    // Define the addresses we want to map.
    var clubs = addr;

    // Create a new Geocoder
    if (first_call == 0){
        geocoder = new google.maps.Geocoder(); // var deleted
    }
    // Locate the address using the Geocoder.
    geocoder.geocode( { "address": clubs }, function(results, status) {
        // If the Geocoding was successful
        if (status == google.maps.GeocoderStatus.OK) {
            if (first_call == 0){
                // Create a Google Map at the latitude/longitude returned by the Geocoder.
                // Create Once
                console.log("Initializing Map");
                myOptions = {
                    zoom: 16,
                    center: results[0].geometry.location,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                };
                //Initialise once
                map = new google.maps.Map(document.getElementById("map"), myOptions);
            }
            // Add a marker at the address.
            console.log("Plotting address");
            var marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location
            });

            first_call = first_call + 1;
            console.log (first_call);
        } else {
                try {
                    console.error("Geocode was not successful for the following reason: " + status);
                } catch(e) {}
            }
    });
    // wrong place because of async call: map is never initialized
    //first_call = first_call + 1;
    //console.log (first_call);
}

var addresses = ['Paris', 'London', 'Berlin'];
for (var i = 0; i < addresses.length; i++) {
    map_function(addresses[i]);
}

</script>

Upvotes: 1

akamaozu
akamaozu

Reputation: 705

Just a bit of output templating mishap. Nothing big. I've rewritten it properly for you.

<?php
while($row = mysqli_fetch_array($result)){
    $addr = $row['ADDRESS'];
    echo '<script type="text/javascript">map_function(' . $addr . ');</script>';
?>

Upvotes: 0

Related Questions