google maps show multiple location (Error: locations[i] is undefined) - javascript

I am trying to show multiple users location using Google Map API, I have to show all value from master_service_provider table for this I am using while loop.
But I am getting JavaScript error Type Error: locations[i] is undefined.
<div id="map"></div>
<script>
var map;
function initMap() {
var i = '0';
<?php
$result=$conn->query("SELECT * FROM `master_service_provider`");
$a=0;
while($row = mysqli_fetch_array($result)) {
$service_provider_id = $row['id'];
$fullname = $row['fullname'];
$fulladdress = $row['fulladdress'];
$phone = $row['phone'];
$lat = $row['lat'];
$lng = $row['lng'];
?>
var <?php echo 's'.$phone; ?> = {
info: '<h3><?php echo $fullname; ?></h3>\
<h4><?php echo $fulladdress; ?></h4>\
View Info',
lat: <?php echo $lat; ?>,
long: <?php echo $lng; ?>
};
var locations = [
[<?php echo 's'.$phone; ?>.info, <?php echo 's'.$phone; ?>.lat, <?php echo 's'.$phone; ?>.long, <?php echo $a++; ?>],
];
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
i++;
<?php } ?>
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 11,
center: new google.maps.LatLng(19.198313, 72.893533),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow({});
var marker;
}
</script>

It should be something like this, I think.
Fill the ... parts yourself, but keep the general structure of the code.
Let me know if you get it to work
<?php
...
// do this on top, not in the middle of javascript
$result = $conn->query("SELECT id, lat, lng, fullname, fulladdress, phone FROM master_service_provider"); // don't use *, specify the columns you want
$mydata = array();
while($row = mysqli_fetch_assoc($result)) { // use _assoc rather than _array
$mydata[] = $row ; // push current row to the data object
}
// now we translate this php array to a javascript array of objects.
// it should resemble something like:
// var locations = [ {"id": "1", "lat":"4.51", "lng":"50.53", "fullname":"John Smith", ... }, {"id": "2", lat":"5.14", ...} ] ;
// use json_encode() to realize this
echo '<script>var locations = '. json_encode($mydata) .' ;</script>';
?>
<script>
var map;
function initMap() {
...
for(var i=0; i<locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i]['lat'], locations[i]['lng']),
title: locations[i]['fullname'],
map: map
});
...
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent('phone: ' + locations[i]['phone']);
infowindow.open(map, marker);
}
})(marker, i));
}
...
}
</script>

Related

Trying to get markers dynamically from database using php and javascript

I am trying to get markers dynamically from the database using sql and php. The problem that i am facing is making the marker array in javascript. I have already referred the questions asked on stackoverflow but no luck...
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
alert("Geolocation is not supported by this browser.");
}
}
function showPosition(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
initMap(latitude,longitude);
addMarker(latitude,longitude);
}
function initMap(latitude,longitude){
var options = {center :{lat:latitude, lng :longitude} ,
zoom:8
}
var map = new google.maps.Map(document.getElementById('map'),options);
var marker = new google.maps.Marker({
position:{lat:latitude, lng :longitude},
map:map
})
}
var markers = [
<?php
require_once '../includes/dbconfig.inc.php';
$marker_fetcher = "SELECT ad_lat,ad_long FROM `tbl_ads`";
$result = mysqli_query($conn,$marker_fetcher);
while ($row = mysqli_fetch_assoc($result)) {
$lat = $row['ad_lat'];
$long = $row['ad_long'];
echo '{';
echo $lat;
echo ',';
echo $long;
echo '},';
}
?>
];
function addMarker(props){
alert(markers.length)
}
$(document).ready(function(){
getLocation();
});
javascript from source
{19.1643153,72.98971789999996},{19.1816553,72.9711542},{19.2403305,73.13053949999994},{29.6856929,76.99048249999998},{19.2532887,73.13668610000002},{19.2532887,73.13668610000002},{19.2292364,72.85967119999998},{19.2292364,72.85967119999998},{19.0606917,72.83624970000005},{18.5596581,73.7799374},{19.157935,72.99347620000003},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{19.2403305,73.13053949999994},{19.157935,72.99347620000003},{19.157935,72.99347620000003},{19.157935,72.99347620000003},{19.157935,72.99347620000003},{53.9332706,-116.5765035},{19.157935,72.99347620000003},{19.2183307,72.97808970000006},{19.157935,72.99347620000003},{53.9332706,-116.5765035},{46.227638,2.213749000000007},{19.157935,72.99347620000003},{19.157935,72.99347620000003},
The array of marker positions is not a valid javascript array. Make the positions to be google.maps.LatLngLiteral objects. Change the code that generates the javascript for your markers array from:
var markers = [
<?php
require_once '../includes/dbconfig.inc.php';
$marker_fetcher = "SELECT ad_lat,ad_long FROM `tbl_ads`";
$result = mysqli_query($conn,$marker_fetcher);
while ($row = mysqli_fetch_assoc($result)) {
$lat = $row['ad_lat'];
$long = $row['ad_long'];
echo '{';
echo $lat;
echo ',';
echo $long;
echo '},';
}
?>
];
To:
var markers = [
<?php
require_once '../includes/dbconfig.inc.php';
$marker_fetcher = "SELECT ad_lat,ad_long FROM `tbl_ads`";
$result = mysqli_query($conn,$marker_fetcher);
while ($row = mysqli_fetch_assoc($result)) {
$lat = $row['ad_lat'];
$long = $row['ad_long'];
echo '{lat:';
echo $lat;
echo ', lng:';
echo $long;
echo '},';
}
?>
];
So your markers array looks like this:
var markers = [
{lat: 19.1643153, lng: 72.98971789999996},
{lat: 19.1816553, lng: 72.9711542},
{lat: 19.2403305, lng: 73.13053949999994},
// ...
];
proof of concept fiddle
code snippet:
var bounds;
var map = null;
function initMap(latitude, longitude) {
var options = {
center: {
lat: latitude,
lng: longitude
},
zoom: 8
}
map = new google.maps.Map(document.getElementById('map'), options);
var marker = new google.maps.Marker({
position: {
lat: latitude,
lng: longitude
},
map: map
})
bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
addMarker(markers[i]);
}
map.fitBounds(bounds);
}
var markers = [{lat:19.1643153, lng:72.98971789999996}, {lat:19.1816553, lng:72.9711542}, {lat:19.2403305, lng:73.13053949999994}, {lat:29.6856929, lng:76.99048249999998}, {lat:19.2532887, lng:73.13668610000002}, {lat:19.2532887, lng:73.13668610000002}, {lat:19.2292364, lng:72.85967119999998}, {lat:19.2292364, lng:72.85967119999998}, {lat:19.0606917, lng:72.83624970000005}, {lat:18.5596581, lng:73.7799374}, {lat:19.157935, lng:72.99347620000003}, {lat:30.900965, lng:75.85727580000002}, {lat:19.2403305, lng:73.13053949999994}, {lat:19.157935, lng:72.99347620000003}, {lat:53.9332706, lng:-116.5765035}, {lat:19.157935, lng:72.99347620000003}, {lat:19.2183307, lng:72.97808970000006}, {lat:46.227638, lng:2.213749000000007}];
function addMarker(props) {
console.log(JSON.stringify(props));
var marker = new google.maps.Marker({
position: props,
map: map
});
console.log(marker.getPosition().toUrlValue(6));
bounds.extend(marker.getPosition());
}
google.maps.event.addDomListener(window, "load", function() {
initMap(19.16, 75.857)
});
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>

How to load the start point and end point in Google map?

I have integrated Google map in my application with routes but I am getting only the end point loaded. I am unable to load the start point and the middle points.
Here is my code:
<?php $final_input_string = ''; ?>
<?php foreach ($riderRoute as $rider) { ?>
<tr>
<?php $currentTime = Yii::$app->Common->formatDateOnlyUS($rider->currentTime); ?>
<td><?php echo $currentTime; ?></td>
<td><?php echo $rider->lat; ?></td>
<td><?php echo $rider->lng; ?></td>
<td><img src="http://maps.google.com/maps/api/staticmap?center=<?php echo $rider->lat; ?>,<?php echo $rider->lng; ?>&zoom=14&size=600x400&maptype=roadmap&sensor=false&language=&markers=color:red|label:none|<?php echo $rider->lat; ?>,<?php echo $rider->lng; ?>" width="400" height="180" style="border:1px solid #CECECE;"> </td>
</div>
</tr>
<?php $final_input_string = ($final_input_string == '') ? $final_input_string . $rider->lat . ',' . $rider->lng : $final_input_string . '|' . $rider->lat . ',' . $rider->lng; ?>
<?php } ?>
<td><div id="map" style="width: 500px; height: 300px"></div></td>
</table>
</div>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script>
var map = null;
var infowindow = new google.maps.InfoWindow();
var bounds = new google.maps.LatLngBounds();
var markers = [
<?php
$long = $rider->lng;
$lat = $rider->lat;
$routes = array("lng" => $long, "lat" => $lat);
$route_points = array($routes);
foreach ($route_points as $points) {
?>
{
"lat": <?php echo "'" . $points['lat'] . "'"; ?>,
"lng": <?php echo "'" . $points['lng'] . "'"; ?>,
},
<?php
}
?>
];
window.onload = function () {
var mapOptions = {
center: new google.maps.LatLng(
parseFloat(markers[0].lat),
parseFloat(markers[0].lng)),
minZoom: 1,
maxZoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var infoWindow = new google.maps.InfoWindow();
var lat_lng = new Array();
var latlngbounds = new google.maps.LatLngBounds();
for (i = 0; i < markers.length; i++) {
var data = markers[i]
var myLatlng = new google.maps.LatLng(data.lat, data.lng);
lat_lng.push(myLatlng);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: data.title
});
latlngbounds.extend(marker.position);
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data.description);
infoWindow.open(map, marker);
});
})(marker, data);
}
map.setCenter(latlngbounds.getCenter());
map.fitBounds(latlngbounds);
//***********ROUTING****************//
//Intialize the Path Array
var path = new google.maps.MVCArray();
//Intialize the Direction Service
var service = new google.maps.DirectionsService();
//Set the Path Stroke Color
var poly = new google.maps.Polyline({map: map, strokeColor: '#4986H7'});
//Loop and Draw Path Route between the Points on MAP
for (var i = 0; i < lat_lng.length; i++) {
if ((i + 1) < lat_lng.length) {
var src = lat_lng[i];
var des = lat_lng[i + 1];
path.push(src);
poly.setPath(path);
service.route({
origin: src,
destination: des,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}, function (result, status) {
if (status == google.maps.DirectionsStatus.OK) {
for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
path.push(result.routes[0].overview_path[i]);
}
}
});
}
}
}
</script>
And my output:

Google maps - Multi markers from database longitude and lattitude not showing on the map

I have this code that takes details from database and put them in php array that later is passed to javascript to generate Google map:
<?php
$query='select name,longitude,latitude from maps';
$result=mysql_query($query) or die();
$num_rows=mysql_num_rows($result);
if($num_rows > 0){
for($i=0;$i<$num_rows;$i++){
$row=mysql_fetch_row($result);
$location[]= $row[0].', '.$row[2].', '.$row[1].','.($i+1);
}
//this creates the following array
array(4) {
[0]=> string(44) "Travel agent Marko, 42.5624525, 27.5263493,1"
[1]=> string(44) "Travel agent Marko, 42.5632957, 27.5267364,2"
[2]=> string(54) "Travel agent 'Planet Travel', 42.5609811, 27.5263934,3"
[3]=> string(56) "Travel agent 'Planet Travel' 2, 42.5642942, 27.5266121,4"
}
?>
<script type="text/javascript">
var loc = <?php echo json_encode($location); ?>;
var locations = [
[loc]
];
var map = new google.maps.Map(document.getElementById('googlemap'), {
zoom: 10,
center: new google.maps.LatLng(42.5624525, 27.5263493),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
alert(locations.length);
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
</script>
<?php
}
?>
my question is why markers don't appear on the map? No error is returned, but no markers too.
Do I have to move javascript code within php loop?
if I alert locations.length I got 1 as locations.length. Why js count the array of locations as 1 location? Thanks in advance !
Change this:
var loc = <?php echo json_encode($location); ?>;
var locations = [
[loc]
];
to this:
var locations = <?php echo json_encode($location); ?>;
And the loop should be:
for (i = 0; i < locations.length; i++) {
loc_array = locations[i].split(",");
marker = new google.maps.Marker({
position: new google.maps.LatLng(loc_array[1], loc_array[2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(loc_array[0]);
infowindow.open(map, marker);
}
})(marker, i));
}

parse xml with php , google maps api v3 markers

I'm trying to find a way to use the function initialize inside a php file.i parse the xml file with the file_get_contents
$xml = file_get_contents('http://www.123.org/upload/123.xml');
include 'xml_regex.php';
$news_items = element_set('item', $xml);
foreach($news_items as $item) {
$description = value_in('description', $item);
$glat = value_in( 'glat', $item );
$glon = value_in( 'glon', $item );
$item_array[] = array(
'description' => $description,
'glat'=>$glat,
'glon'=>$glon
);
}
the function initialize
</script>
function initialize() {
var mapOptions = {
zoom: 6,
center: new google.maps.LatLng( 38.822590,24.653320 )
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
<?php foreach ( $item_array as $item ) {
//how can i use this lines inside the loop?
//var latlng = new google.maps.LatLng(parseFloat("<?php $glat ?>"),
//parseFloat("<?php $glon ?>"));
//alert (latlng);
//also inside the loop i wanna use the createMarker funciton
}?>
</script>
Any ideas?
Finally i found the way!Just quote the code.Maybe it will help someone in the future!
<?php foreach ( $item_array as $item ) : ?>
var latlng = new google.maps.LatLng(parseFloat(<?php echo $item['glat']; ?>),
parseFloat(<?php echo $item['glon']; ?>));
if ( '<?php echo $item["temp"]; ?>' <= "1 °C" ) {
var marker = createMarker( latlng,cold );
}
function createMarker( latlng,cold ) {
var marker = new google.maps.Marker({
position: latlng,
map: map,
icon: cold
});
return marker;
}

I'm trying to position google maps with a table row click

On my webpage when the page loads it loads a table generated by content from my database, and all markers are instantly loaded on the map, but I'd like to be able to click on the table row to center and zoom on the marker that it represents, I'm trying to figure it out but I'm new to JQuery/Javascript just kind of learning as I go.
Here is my JQuery function I'm working on..
$("table#listOfStops").find('tr').each(function() {
$(this).on('click', function() {
alert(arrMarkers.length);
var num = $(this).data("num");
for (var i = 0; i < arrMarkers.length; i++) {
if ( arrMarkers.id == 'marker'+num) {
map.setCenter(arrMarkers[i].position);
map
}
}
});
});
Here is my table:
<table id="listOfStops" class="table table-striped">
<thead>
<tr>
<th>Stop #</th>
<th>Street Name</th>
</tr>
</thead>
<tbody>
<?php
$i = 0;
while($stmt -> fetch()) {
echo '<tr id="' . $i . '">';
echo '<td>' . $gStopNumber . '</td>';
echo '<td>' . $gStreetName . '</td>';
echo '</tr>';
$i++;} $stmt -> close(); $mysqli -> close(); ?>
</tbody>
</table>
On page load it loads this initialize function:
function initialize() {
geocode = new google.maps.Geocoder();
var mapOptions = {
zoom: 10,
center: new google.maps.LatLng(56.7626362, -111.379652),
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: false,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE
}
};
map = new google.maps.Map(document.getElementById('gmaps'),
mapOptions);
google.maps.event.addListener(map, 'click', function(event) {
var latitude = event.latLng.lat();
var longitude = event.latLng.lng();
deleteOverlays();
addMarker(event.latLng);
updateTextFields(latitude, longitude);
});
<?php while($stmt -> fetch()) { ?>
var long = "<?php echo $gLongitude ?>";
var lati = "<?php echo $gLatitude; ?>";
var title = "<?php echo $gTitle; ?>"
setMarker(lati, long, title);
<?php } $stmt -> close(); $mysqli -> close();?>
}
and then sets each marker to the map and pushes them to an array using the setMarker function:
function setMarker(lat,lon, markerTitle) {
var latLonMarker = new google.maps.LatLng(lat,lon);
marker = new google.maps.Marker({
position: latLonMarker,
map: map,
icon: 'icon.png',
title: markerTitle
});
google.maps.event.addListener(marker, 'dragend', function() {
$('#inputLatitude').val(this.getPosition().lat());
$('#inputLongitude').val(this.getPosition().lng());
});
arrMarkers.push(marker);
}
I'm just having an impossibly hard time matching the table row to the proper marker spot in the marker array to set the position something like map.setPosition(arrMarkers[i]);
Thanks in advance.
The jquery.each function supplies the index of the each result.
If you modify the query to .find('tbody tr') the index should match the position in the array
So something like:
$("table#listOfStops").find('tbody tr').each(function(idx) {
var rowNumber=idx;
$(this).on('click', function() {
map.setCenter(arrMarkers[rowNumber].getPosition());
});
});

Categories