Add Google Maps Markers from an array

I am trying to add Google Markers on my map from an array “gps” and “status”. The status can either be active or disabled. There are multiple location that have to be displayed on the map. I have managed to add the markers manually but i need help with adding the markers from the array using something like the “foreach or while loop”.

This is the array

Array
(
    [0] => Array
        (
            [status] => active
            [gps] => -26.269704939193858,31.085300236009065
        )

    [1] => Array
        (
            [status] => active
            [gps] => -26.29697452399767,31.120804981797505
        )

)

This is my map below.

var handleGoogleMapSetting = function() {
	"use strict";
	var mapDefault;
	var locationRio = new google.maps.LatLng(-26.297106, 31.119429);
	var mapOptions = {
		zoom: 13,
		center: locationRio,
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		disableDefaultUI: true,
		gestureHandling: 'cooperative'
	};

	mapDefault = new google.maps.Map(document.getElementById('google-map-default'), mapOptions);

	var iconBase = 'include/images/';

	var icons = {
		active: {
			icon: iconBase + 'internet-online.png'
		},
		disabled: {
			icon: iconBase + 'internet-offline.png'
		},
		blocked: {
			icon: iconBase + 'internet-offline.png'
		}
	};

	var features = [
	{
		locationRio: new google.maps.LatLng(-26.269704939193858,31.085300236009065),
		type: 'active'
	}, {
		locationRio: new google.maps.LatLng(-26.490778193095103,31.38347625732422),
		type: 'disabled'
	}
	];

	for (var i = 0; i < features.length; i++) {
		var marker = new google.maps.Marker({
			position: features[i].locationRio,
			icon: icons[features[i].type].icon,
			map: mapDefault,
      });
	};
	$(window).resize(function() {
		google.maps.event.trigger(mapDefault, "resize");
	});
	
	var defaultMapStyles = [];
	var flatMapStyles = [{"stylers":[{"visibility":"off"}]},{"featureType":"road","stylers":[{"visibility":"on"},{"color":"#ffffff"}]},{"featureType":"road.arterial","stylers":[{"visibility":"on"},{"color":"#fee379"}]},{"featureType":"road.highway","stylers":[{"visibility":"on"},{"color":"#fee379"}]},{"featureType":"landscape","stylers":[{"visibility":"on"},{"color":"#f3f4f4"}]},{"featureType":"water","stylers":[{"visibility":"on"},{"color":"#7fc8ed"}]},{},{"featureType":"road","elementType":"labels","stylers":[{"visibility":"off"}]},{"featureType":"poi.park","elementType":"geometry.fill","stylers":[{"visibility":"on"},{"color":"#83cead"}]},{"elementType":"labels","stylers":[{"visibility":"off"}]},{"featureType":"landscape.man_made","elementType":"geometry","stylers":[{"weight":0.9},{"visibility":"off"}]}]; 
	var turquoiseWaterStyles = [{"featureType":"landscape.natural","elementType":"geometry.fill","stylers":[{"visibility":"on"},{"color":"#e0efef"}]},{"featureType":"poi","elementType":"geometry.fill","stylers":[{"visibility":"on"},{"hue":"#1900ff"},{"color":"#c0e8e8"}]},{"featureType":"landscape.man_made","elementType":"geometry.fill"},{"featureType":"road","elementType":"geometry","stylers":[{"lightness":100},{"visibility":"simplified"}]},{"featureType":"road","elementType":"labels","stylers":[{"visibility":"off"}]},{"featureType":"water","stylers":[{"color":"#7dcdcd"}]},{"featureType":"transit.line","elementType":"geometry","stylers":[{"visibility":"on"},{"lightness":700}]}];
	var icyBlueStyles = [{"stylers":[{"hue":"#2c3e50"},{"saturation":250}]},{"featureType":"road","elementType":"geometry","stylers":[{"lightness":50},{"visibility":"simplified"}]},{"featureType":"road","elementType":"labels","stylers":[{"visibility":"off"}]}];
	var oldDryMudStyles = [{"featureType":"landscape","stylers":[{"hue":"#FFAD00"},{"saturation":50.2},{"lightness":-34.8},{"gamma":1}]},{"featureType":"road.highway","stylers":[{"hue":"#FFAD00"},{"saturation":-19.8},{"lightness":-1.8},{"gamma":1}]},{"featureType":"road.arterial","stylers":[{"hue":"#FFAD00"},{"saturation":72.4},{"lightness":-32.6},{"gamma":1}]},{"featureType":"road.local","stylers":[{"hue":"#FFAD00"},{"saturation":74.4},{"lightness":-18},{"gamma":1}]},{"featureType":"water","stylers":[{"hue":"#00FFA6"},{"saturation":-63.2},{"lightness":38},{"gamma":1}]},{"featureType":"poi","stylers":[{"hue":"#FFC300"},{"saturation":54.2},{"lightness":-14.4},{"gamma":1}]}];
	var cobaltStyles  = [{"featureType":"all","elementType":"all","stylers":[{"invert_lightness":true},{"saturation":10},{"lightness":10},{"gamma":0.8},{"hue":"#293036"}]},{"featureType":"water","stylers":[{"visibility":"on"},{"color":"#293036"}]}];
	var darkRedStyles   = [{"featureType":"all","elementType":"all","stylers":[{"invert_lightness":true},{"saturation":10},{"lightness":10},{"gamma":0.8},{"hue":"#000000"}]},{"featureType":"water","stylers":[{"visibility":"on"},{"color":"#293036"}]}];

	$('[data-map-theme]').click(function() {
		var targetTheme = $(this).attr('data-map-theme');
		var targetLi = $(this).closest('li');
		var targetText = $(this).text();
		var inverseContentMode = false;
		$('#map-theme-selection li').not(targetLi).removeClass('active');
		$('#map-theme-text').text(targetText);
		$(targetLi).addClass('active');
		
		switch(targetTheme) {
			case 'flat':
			mapDefault.setOptions({styles: flatMapStyles});
			break;
			case 'turquoise-water':
			mapDefault.setOptions({styles: turquoiseWaterStyles});
			break;
			case 'icy-COLOR_BLUE':
			mapDefault.setOptions({styles: icyBlueStyles});
			break;
			case 'cobalt':
			mapDefault.setOptions({styles: cobaltStyles});
			inverseContentMode = true;
			break;
			case 'old-dry-mud':
			mapDefault.setOptions({styles: oldDryMudStyles});
			break;
			case 'dark-red':
			mapDefault.setOptions({styles: darkRedStyles});
			inverseContentMode = true;
			break;
			default:
			mapDefault.setOptions({styles: defaultMapStyles});
			break;
		}

		if (inverseContentMode === true) {
			$('#content').addClass('content-inverse-mode');
		} else {
			$('#content').removeClass('content-inverse-mode');
		}
	});
};

var MapGoogle = function () {
	"use strict";
	return {
		//main function
		init: function () {
			handleGoogleMapSetting();
		}
	};
}();

$(document).ready(function() {
	MapGoogle.init();
});

and this is my index.php

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8" />
	<title>NMS</title>

</head>
<body>

	<!-- begin #content -->
	<div id="content" class="content content-full-width content-inverse-mode">
		<div class="map">
			<div id="google-map-default" class="height-full width-full"></div>
			<!-- begin map-float-table -->
			<div class="map-float-table d-none d-xl-block p-10">
				<!-- begin scrollbar -->
				<div id="autoupdate" data-scrollbar="false" style="position: relative;overflow: hidden;width: auto;height: auto; font-size:.7rem;">
				</div>
				<!-- end scrollbar -->
			</div>
			<!-- end map-float-table -->
		</div>
	</div>
	<!-- end #content -->

	<!-- ================== BEGIN PAGE LEVEL JS ================== -->
	<script async defer
	src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&callback=initMap">
</script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&amp;sensor=false"></script>
<!-- ================== END PAGE LEVEL JS ================== -->
</body>
</html>

you can replace var features = [ and following by a PHP foreach.

I have done what you have suggested but its still not wotking

I have replaced

	var features = [
	{
		locationRio: new google.maps.LatLng(-26.269704939193858,31.085300236009065),
		type: 'active'
	}, {
		locationRio: new google.maps.LatLng(-26.490778193095103,31.38347625732422),
		type: 'disabled'
	}
	];

with

	var features = [
	<?php
		foreach($customers_list as $item)
		{
			locationRio: new google.maps.LatLng(echo $item['gps'];),
			type: 'echo $item['status'];'
		}       
	?>  
	];

and you dont get an error message for that?

so i have cleaned up my code a bit

<!DOCTYPE html>
<html>
  <head>
    <title>Custom Markers</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <style>
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 100%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
  </head>
  <body>




    <div id="map"></div>

    <?php
include 'include/api/SplynxApi.php';

$api_url = 'XXX'; // please set your Splynx URL

$admin_login = "XXX"; // Splynx administrator login
$admin_password = "XXX"; // Splynx administrator password

$api = new SplynxAPI($api_url);
$api->setVersion(SplynxApi::API_VERSION_2);

$isAuthorized = $api->login([
	'auth_type' => SplynxApi::AUTH_TYPE_ADMIN,
	'login' => $admin_login,
	'password' => $admin_password,
]);


if (!$isAuthorized) {
    exit("Authorization failed!\n");
}

$customerApiUrl = "admin/customers/customer/";

print "<pre>";

$result_customers = $api->api_call_get($customerApiUrl);
$customers_list = $api->response;
if ($result_customers) {
    // print_r($api->response);
} else {
    print "Fail! Error code: $api->response_code\n";
    // print_r($api->response);
}
?>


    <script>
      var map;
      function initMap() {
        map = new google.maps.Map(
            document.getElementById('map'),
            {center: new google.maps.LatLng(-26.297106, 31.119429), zoom: 16});

        var iconBase =
            'https://developers.google.com/maps/documentation/javascript/examples/full/images/';

        var icons = {
          parking: {
            icon: iconBase + 'parking_lot_maps.png'
          },
          library: {
            icon: iconBase + 'library_maps.png'
          },
          info: {
            icon: iconBase + 'info-i_maps.png'
          }
        };

        var features = [
        <?php
		foreach($customers_list as $item)
          {
            position: new google.maps.LatLng(echo $item['gps'];),
            type: 'echo $item['status'];'
          }
          ?>  
        ];

        // Create markers.
        for (var i = 0; i < features.length; i++) {
          var marker = new google.maps.Marker({
            position: features[i].position,
            icon: icons[features[i].type].icon,
            map: map
          });
        };
      }
    </script>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&callback=initMap">
    </script>
  </body>
</html>

and this is the error message i get


Parse error: syntax error, unexpected 'echo' (T_ECHO) in /opt/lampp/htdocs/pppoe/map.php on line 91

you’re mixing up JS and PHP at that point. at least you want to echo a whole string like

echo "{
		locationRio: new google.maps.LatLng(".$lat.",".$lon."),
		type: '".$status."'
	}"
Sponsor our Newsletter | Privacy Policy | Terms of Service