0

I am creating a lot of content dynamically with JavaScript and right now I think my code looks terrible. I am looking for a way to clean it up a bit so if someone has some suggestions for a better way to replicate what I am doing below I would love to hear it. Thanks

var nearestContent = "<h2>Nearest Dealers:</h2>" + "<h3>" + nearest[0][2] + "</h3><p>" + nearest[0][1] + "<BR />" + nearest[0][3] + ", " + nearest[0][4] + ' ' + nearest[0][5] + "<BR />" + milesAway + " Miles away!" + 
                             "<BR />" + "<a href='" + nearest[0][6] + "'>" + nearest[0][6] + "</a>" + "</p>";                            
document.getElementById("NearestLocation").innerHTML=nearestContent;

Here is my maps.js file:

    var markers = new Array();
    var infoWindowContent = [];
    var geocoder;
    var map;
    var result;
    var nearest = new Array();



        function initialize() {
            for (var i = 0; i < data.Latitude.length; i++)
            {
                markers[i] = [(data.Latitude[i]), (data.Longitude[i]), 
                              (data.Address[i]), (data.Company[i]), 
                              (data.City[i]), (data.State[i]),
                              (data.Website[i]), (data.Group[i]), (data.Zip[i])];
            }       

            var icon;
            var bounds = new google.maps.LatLngBounds();
            var mapOptions = {
                mapTypeId: 'roadmap'
            };
            geocoder = new google.maps.Geocoder();

            // Display a map on the page
            map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
            map.setTilt(45);

            // Info Window Content
            for(i=0; i< markers.length; i++) {
                var testContent = ['<div class="info_content">' + '<h3>' + markers[i][3] + '</h3>' + '<p>' + markers[i][2] + '<BR />' + markers[i][4] + ', ' + markers[i][5] + ' ' + markers[i][8] + '</p>' + '<BR /> <a href="' + markers[i][6] +'">' + markers[i][6] +'</a>' +'</div>'];
                infoWindowContent.push(testContent);
            }
            // Display multiple markers on a map
            var infoWindow = new google.maps.InfoWindow(), marker, i;

            // Loop through our array of markers & place each one on the map  
            for( i = 0; i < markers.length; i++ ) {
                var position = new google.maps.LatLng(markers[i][0], markers[i][1]);
                switch (markers[i][7]) {
                    case "Mobile Showroom":
                        icon = "red-dot";
                        break;
                    case "NS Dealer":
                        icon = "blue-dot";
                        break;
                    case "SD Dealer":
                        icon = "yellow-dot";
                        break;
                    case "S Dealer":
                        icon = "green-dot";
                        break;
                    default:
                        icon=   "orange-dot";
                        break;
                }
                icon = "mapIcons/" + icon + ".png";
                bounds.extend(position);
                marker = new google.maps.Marker({
                    position: position,
                    map: map,
                    icon: new google.maps.MarkerImage(icon, null, null, null, new google.maps.Size(20, 20)),
                    title: markers[i][2]
                });

                // Allow each marker to have an info window    
                google.maps.event.addListener(marker, 'click', (function(marker, i) {
                    return function() {
                        document.getElementById("DealerInfo").innerHTML=infoWindowContent[i][0];
                    };
                })(marker, i));

                // Automatically center the map fitting all markers on the screen
                map.fitBounds(bounds);
            }
        }




        function codeAddress() {
          var address = document.getElementById('address').value;
          geocoder.geocode( { 'address': address}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                result = results[0].geometry.location;
                map.setZoom(8),
                map.setCenter(results[0].geometry.location);
                CalculateNearestDealer(results[0].geometry.location);
              var marker = new google.maps.Marker({
                  map: map,
                  icon: "mapIcons/beachflag.png",
                  position: results[0].geometry.location
              });

            } else {
              alert('Geocode was not successful for the following reason: ' + status);
            }
          });
        }





        function CalculateNearestDealer(results) {
        for (var i = 0; i < data.Latitude.length; i++)
        {
            var markers = [(data.Latitude[i]), (data.Longitude[i]), 
                          (data.Address[i]), (data.Company[i]), 
                          (data.City[i]), (data.State[i]),
                          (data.Website[i])];
            var userLocation = new google.maps.LatLng(result.ob, result.pb);
            var dealerLocation = new google.maps.LatLng(markers[0], markers[1]);
            var distance = google.maps.geometry.spherical.computeDistanceBetween(userLocation, dealerLocation);
                nearest[i] = [(distance/1609.344), (data.Address[i]), (data.Company[i]), (data.City[i]), (data.State[i]), (data.Zip[i]), (data.Website[i])];
        }

        nearest.sort(function(a,b){return a[0]-b[0];});
        var milesAway = Math.round( nearest[0][0] );
        var nearestContent = Mustache.render("<h2>Nearest Dealers:</h2><h3>{{dealerName}}</h3>"
            + "<p>{{description}}<br/>{{info1}}, {{info2}}<br/>{{distance}} Miles away!<br/><a href='{{href}}'>{{hrefTitle}}</a></p>", {
            dealerName: nearest[0][2],
            description: nearest[0][1],
            info1: nearest[0][3],
            info2: nearest[0][4],
            href: nearest[0][6],
            hrefTitle: nearest[0][6],
            distance: milesAway
        });
        document.getElementById("NearestLocation").innerHTML=nearestContent;
        document.write("<p>" + nearest[0] + "</p>");
   }

HTML file:

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Simple markers</title>
    <link rel="stylesheet" href="css/style.css" />
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&v=3&libraries=geometry"></script>
    <script type="text/javascript" src="js/mustache.js"></script>
    <script type="text/javascript" src="js/maps.js"></script>

    </head>

<body>
    <div id="container">
    <div id="map_canvas"></div>
    <?php

        require 'DB.php';

        $stmt = "SELECT dealerinfo.Company, small.Address, dealerinfo.City, dealerinfo.State, dealerinfo.Phone, dealerinfo.Zip, dealerinfo.Website, small.Lat, small.Long, dealerinfo.Group
                 FROM small
                 LEFT JOIN dealerinfo ON small.Address = dealerinfo.Address
                 ORDER BY small.Address";

        $corodinates = array();
        $i = 0;
        foreach($DB->query($stmt) as $row) {

            $corodinates['Latitude'][$i] = $row['Lat'];
            $corodinates['Longitude'][$i] = $row['Long'];
            $corodinates['Address'][$i] = $row['Address'];
            $corodinates['Company'][$i] = $row['Company'];
            $corodinates['City'][$i] = $row['City'];
            $corodinates['State'][$i] = $row['State'];
            $corodinates['Zip'][$i] = $row['Zip'];
            $corodinates['Website'][$i] = $row['Website'];
            $corodinates['Group'][$i] = $row['Group'];
            $corodinates['Phone'][$i] = $row['Phone'];
            $i++;
        }
    ?>

    <div id="CustomerAddress">
        <input type="textbox" id="address"/>
        <input type="button" value="Locate" onclick="codeAddress()">
    </div>

    <div id="DealerInfoContainer">
        <div id="NearestLocation"></div>
            <div id="DealerInfo">
                <h2>Test Dealer Network</h2>
                <p>Please enter the location of customer above or click a marker to view information about dealer.</p>
            </div>
        </div>
    </div>
    <script>var data = <?php echo json_encode($corodinates); ?>;</script>
    <script>initialize();</script>
</body>

</html>
2
  • 1
    Google for "client side template engine". Commented Jan 28, 2014 at 14:54
  • use an object for "nearest", this way you could have: nearest.dealer, nearest.url, nearest.description, ... Commented Jan 28, 2014 at 14:55

2 Answers 2

1

Looks like you should look into templating.

As an example, with Mustache it could look like this:

var nearestContent = Mustache.render("<h2>Nearest Dealers:</h2><h3>{{dealerName}}</h3>"
    + "<p>{{description}}<br/>{{info1}}, {{info2}}<br/>{{distance}} Miles away!<br/><a href='{{href}}'>{{hrefTitle}}</a></p>", {
    dealerName: nearest[0][2],
    description: nearest[0][1],
    info1: nearest[0][3],
    info2: nearest[0][4],
    href: nearest[0][6],
    hrefTitle: nearest[0][6],
    distance: milesAway
});
document.getElementById("NearestLocation").innerHTML=nearestContent;

Here's a demo

Sign up to request clarification or add additional context in comments.

7 Comments

I have copied your code and implemented the mustache.js file but I am getting two errors. I have a main html file where I include the mustache.js file then I include my external JS file with my functions that generate the html which is where I pasted your code. The errors I am getting are Uncaught SyntaxError: Unexpected token < mustache.js : line 6 and Uncaught ReferenceError: Mustache is not defined maps.js : line 121
Sorry, I can't reproduce these. Does your editor have syntax highlighting? Did you mess up the quotes somehow?
When I dropped it directly into my code It gave me invalid syntax errors saying that I needed a semicolon where you had put commas it actually wouldn't run the script until I added a semicolon </a></p>");<There
You're right of course! The bracket should be behind both function parameters, so, including the object with the data. I fixed the snippet. Sorry about that!
Thanks but I am still getting the errors for some reason I will update my question with all of my code
|
1

The merging of JS data into HTML is best handled using a template engine.

You create an HTML "template" with placeholders for data values and then use the engine to generate the HTML that you wish to publish by replacing those placeholders with your data.

You might want to look at

Or, indeed, any of the major JS development frameworks, as they tend to include some form of template engine.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.