Click here to Skip to main content
15,868,019 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
Hi Team

I have debug my code, i am experience this issue Uncaught syntax error. Kindly please help me to resolve this issue maybe i could be missing some javascript library, please advice me and help mates.

What I have tried:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.SqlClient;
using System.Configuration;

namespace eNtsaRegistrationTraining.Controllers
{
    public class MapsController : Controller
    {
        // GET: Maps
        public ActionResult GoogleMaps()
        {
            string markers = "[";
            string conString = ConfigurationManager.ConnectionStrings["eNtsaRegistration"].ConnectionString;
            SqlCommand cmd = new SqlCommand("SELECT * FROM dbo.Locations");
            using (SqlConnection con = new SqlConnection(conString))
            {
                cmd.Connection = con;
                con.Open();
                using(SqlDataReader sdr = cmd.ExecuteReader())
                {
                    while(sdr.Read())
                    {
                        markers += "{";
                        markers += string.Format("'title': '{0}',", sdr["Name"]);
                        markers += string.Format("'lat:' '{0}',", sdr["Latitute"]);
                        markers += string.Format(" 'lng': '{0}',", sdr["Longitute"]);
                        markers += string.Format("'description': '{0}'", sdr["Description"]);
                        markers += "},";
                    }
                }
                con.Close();
            }

            markers += "];";
            ViewBag.Makers = markers;

            return View();
        }
    }
}


{
    ViewBag.Title = "GoogleMaps";
    Layout = null;
}

<pre lang="Javascript"><!DOCYTPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>eNtsa Office Location</title>
</head>
<body>
    <div id="dvMap" style="width: 500px; height: 500px">
    </div>
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB9vzf41FPK5l9NX0wCFgx_x873YuSq9KQ"></script>
    <script type="text/javascript">
        var markers = @Html.Raw(ViewBag.Markers);
        window.onload = function () {
            var mapOptions = {
                center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
                zoom: 8,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            var infoWindow = new google.maps.InfoWindow();
            var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
            for (i = 0; i < markers.length; i++) {
                var data = markers[i]
                var myLatlng = new google.maps.LatLng(data.lat, data.lng);
                var marker = new google.maps.Marker({
                    position: myLatlng,
                    map: map,
                    title: data.title
                });
                (function (marker, data) {
                    google.maps.event.addListener(marker, "click", function (e) {
                        infoWindow.setContent(data.description);
                        infoWindow.open(map, marker);
                    });
                })(marker, data);
            }
        }
    </script>
</body>

</html>
Posted
Updated 10-Mar-20 2:03am
v2
Comments
Richard MacCutchan 10-Mar-20 5:23am    
Where does the error occur?
gcogco10 10-Mar-20 5:24am    
var markers = @Html.Raw(ViewBag.Markers);
Jon McKee 10-Mar-20 5:40am    
What does ViewBag.Markers contain? It looks like it's an array, in which case I'm pretty sure you don't need @Html.Raw() because all that does is prevent the default Razor encoding for strings from happening by wrapping the non-encoded string in an IHtmlString. I'm actually not sure what happens if you pass it a non-string.
gcogco10 10-Mar-20 5:44am    
I omit to put the logic for my Controller, I invoke using Marker from the controller, that variable is accessing those fields as being declared by the controller.

ViewBag.Makers = markers;

That might be your issue. Makers should be Markers. So your javascript is probably rendering like var markers = ; causing a syntax error.
 
Share this answer
 
Comments
gcogco10 10-Mar-20 6:08am    
Thanks Jon, now i am getting this Uncaught TypeError: Cannot read property 'lat' of undefined
at window.onload (GoogleMaps:19) center: new google.maps.LatLng(markers[0].lat, markers[0].lng), The name i defined there within the controller. Please advice
Jon McKee 10-Mar-20 6:11am    
"'lat:' '{0}'," should be "'lat': '{0}',". The single quote is in the wrong spot.

I also notice that the way you're concatenating the objects, you will end up with an extra ',' at the end. Ex: [ { .... }, { .... },]. So you might need to delete that last character before doing markers +="];".

Something like this should work:
let commaIndex = markers.lastIndexOf(",");
if (commaIndex > 0) {
  markers = markers.substring(0, commaIndex);
}
gcogco10 10-Mar-20 6:24am    
Thanks mate, i removed the dbo.Locations to be actually Table name 'Locations' only. Now my maps dont load well and dont know why. please assist
Jon McKee 10-Mar-20 6:29am    
Is it a single-schema database? If it worked with the schema there why remove it? Never hurts to be specific even if there is only one schema.
gcogco10 10-Mar-20 6:33am    
Its a single schema database
Don't try to build a JSON string manually. Instead, build a collection of objects, and then use a proper JSON serializer to generate the JSON.

Model:
C#
public class Marker
{
    public string title { get; set; }
    public double lat { get; set; }
    public double lng { get; set; }
    public string description { get; set; }
}
Action:
C#
public ActionResult GoogleMaps()
{
    var markers = new List<Marker>();
    
    string conString = ConfigurationManager.ConnectionStrings["eNtsaRegistration"].ConnectionString;
    using (var con = new SqlConnection(conString))
    using (var cmd = new SqlCommand("SELECT Name, Latitude, Longitude, Description FROM dbo.Locations", con))
    {
        con.Open();
        using (var sdr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
        {
            while (sdr.Read())
            {
                markers.Add(new Marker
                {
                    title = Convert.ToString(sdr["Name"]),
                    lat = Convert.ToDouble(sdr["Latitude"]),
                    lng = Convert.ToDouble(sdr["Longitude"]),
                    description = Convert.ToString(sdr["Description"]),
                });
            }
        }
    }

    ViewBag.Markers = markers;
    return View();
}
View:
Razor
<script>
var markers = @Html.Raw(Json.Encode(ViewBag.Markers));
 
Share this answer
 
v2
Comments
gcogco10 10-Mar-20 8:20am    
Thanks Richard, the challenge i am getting now. This app is not showing my current location within the map. What could i be missing, the location its pointing outside continent(Africa). It should be point to SA(port elizabeth)
Richard Deeming 10-Mar-20 8:28am    
There must be something wrong with your coordinates. I suspect you've got the wrong sign on your latitude - Google expects the degrees North, so you'll need to use -33.9608.
gcogco10 10-Mar-20 8:56am    
OK noted, but i have amended using this logic above. I am getting this error center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
zoom: 8,Uncaught TypeError: Cannot read property '0' of null
Richard Deeming 10-Mar-20 8:59am    
Well that error sounds like you're not actually outputting any markers. You did correct the spelling from Makers to Markers as Jon pointed out, didn't you?

Have a look at the source of the page from your browser to see what the markers variable is set to.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900