1

I am trying to create a code snippet that fetches google map objects like location, marker text from database and add it to html data-attributes so I can use them in javascript easily

I am unable to make js understand the json as json , its rather being treated as string

	jQuery('.map_canvazz').each(function(i,elem) {
		latPos			=	jQuery(this).attr("data-lat");
		longPos			=	jQuery(this).attr("data-long");
		infoDisplay		=	jQuery(this).attr("data-info");
		var objAddresses=	jQuery(this).attr("data-params");
        
      if(typeof objAddresses != 'undefined'){
			console.log(typeof(objAddresses));
			console.log(objAddresses);
			//array of object is treated as string
            // unable to convert array of objects as json
            // todo :- loop through the object of array
		}
      
      })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class='map_canvazz' id='maper1'   data-params='[{"lat":"-36.758435","long":"144.273174","mapTxt":"<div class=\"mapArea\"><div class=\"lineOneMap\">Beyond Medical Education Victorian Office<\/div><div class=\"lineTwoMap\">37 Rowan Street<br>Bendigo VIC 3550, Australia<br>+61 35441 9300<\/div><\/div>"},{"lat":"1111","long":"222","mapTxt":"test"}]'></div>					</div>

2 Answers 2

2

Attribute values can only be strings. If you want to convert a string of JSON into a JavaScript object then you should run it through JSON.parse().

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

1 Comment

I tried using JSON.parse() and I get following error SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
1

Use .data() jq method. It will parse it to array:

jQuery('.map_canvazz').each(function(i, elem) {
  var objAddresses = jQuery(this).data("params");
  for (var i = 0; i < objAddresses.length; i++) {
    var obj = objAddresses[i];
    console.log(obj.lat, obj.long, obj.mapTxt);
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class='map_canvazz' id='maper1' data-params='[{"lat":"-36.758435","long":"144.273174","mapTxt":"<div class=\"mapArea\"><div class=\"lineOneMap\">Beyond Medical Education Victorian Office<\/div><div class=\"lineTwoMap\">37 Rowan Street<br>Bendigo VIC 3550, Australia<br>+61 35441 9300<\/div><\/div>"},{"lat":"1111","long":"222","mapTxt":"test"}]'></div>
</div>

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.