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>
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>
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:
So i have a set of data in my database, the data consist of location id (loc_id), longitude, and latitude. what i want to do is to create a map that consist of marker from all of my location data. what should i do first to create this map? because this is my first time using javascript.
currently the code that i used to show the map :
<script src="http://maps.googleapis.com/maps/api/js"></script>
<script>
function initialize() {
var mapProp = {
center:new google.maps.LatLng(-7.803164,110.3398252), zoom:10, mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
You need to output the data in your database into javascript and then loop through them then add them to your map.
First get the data from your database and make it into a javascript array. FYI my PHP is very rusty
var locations = [
<?php
$query = 'SELECT * FROM sometable';
$result = mysql_query($query);
$currentrow = 0;
while ($row = mysql_fetch_assoc($result)) {
$currentrow++;
echo '{';
echo 'latitude : ' . $row[0] . ',';
echo 'longitude: ' . $row[1] ;
echo '}'.if(currentrow != msqli->num_rows){,}
}
?>
]
Then on the javascript you need to loop through the locations array and create them as markers.
for(var i = 0; i < locations.lengtht; i++){
var myLatLng = {
lat: locations[i].latitude,
lng: locations[i].longitude
};
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Your title'
});
}
I want to have various buttons that open the corresponding info window on a google maps markers. I have looked at answers like THIS but they don't have dynamically created content. I am getting multiple locations from my db and showing them on a page. They have ids which I have added to the button. I have also added the corresponding ids to the markers (as seen HERE).
Now I just need to trigger the correct marker with the correct id. I think my problem is something to do with scope but I'm a bit lost. Using Laravel 5.
Code is all on a page called index.blade.php. User enters address in form which is geocoded to lat/lng then the nearest articles/stores are displayed on index.blade.php using the Articles Controller.
Code:
#extends('template')
#section('content')
#foreach ($articles as $article)
<i class="fa fa-plus-square showMoreDetails" onclick="myClick({{$article->id}});"></i>
#endforeach
#stop
#section('footer')
<script>
var barTitle = [
#foreach($articles as $article)
"{{$article->title}}" ,
#endforeach
];
var barDeal = [
#foreach($articles as $article)
"{{$article->deal}}" ,
#endforeach
];
var infoWindowContent = [];
var markers = [];
var i, marker;
function initialize() {
var map_canvas = document.getElementById('map_canvas');
var myLatlng = new google.maps.LatLng(parseFloat({{ $article->lat }}),parseFloat({{ $article->lng }}));
var map_options = {
center: myLatlng,
zoom: 15,
zoomControl: true,
zoomControlOptions: {
position: google.maps.ControlPosition.BOTTOM_RIGHT
},
scaleControl: true,
panControl: true,
panControlOptions:{
position: google.maps.ControlPosition.BOTTOM_LEFT
},
mapTypeControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(map_canvas, map_options);
var locations = [
#foreach($articles as $article)
[{{$article->lat}}, {{$article->lng}}],
#endforeach
];
var barID = [
#foreach($articles as $article)
{{$article->id}},
#endforeach
];
for (i = 0; i < locations.length; i++) {
infoWindowContent[i] = getInfoWindowDetails(locations[i]);
var location = new google.maps.LatLng(locations[i][0], locations[i][1]);
var marker = new google.maps.Marker({
position: location,
map: map,
id: barID[i],
icon: 'images/happymarker.png'
});
var infowindow = new google.maps.InfoWindow()
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
// infowindow.setContent(barTitle[i]);
infowindow.setContent(infoWindowContent[i]);
infowindow.open(map, marker);
map.panTo(marker.getPosition());
map.setZoom(17);
}
})(marker, i));
markers.push(marker);
}
}
function getInfoWindowDetails(location){
var contentString = '<div id="infoWindowBox">' +
'<h3 id="firstHeading" class="infoWindowTitle">' + barTitle[i] + '</h3>'+
'<div id="bodyContent">'+
'<div>'+ barDeal[i] + '</div>'+
'</div>'+
'</div>';
return contentString;
}
google.maps.event.addDomListener(window, "load", initialize);
function myClick(id){
google.maps.event.trigger(markers[id], 'click');
}
</script>
#stop
My template.blade.php page loads maps like this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=MYKEY&signed_in=true&libraries=places"></script>
Articles Controller:
public function index(Request $request)
{
$lat = $request->get('lat');
$lng = $request->get('lng');
$distance = 1;
$categoryChoice = $request->get('categoryList');
$query = Article::distance($lat, $lng, $distance)
->whereHas('categories', function ($query) use ($categoryChoice) {
$query->whereIn('categories.id', $categoryChoice);
})->get();
$articles = $query;
if(count($articles) == 0)
{
return redirect()->action('HomeController#index');
}
return view('articles.index', compact('categories', 'articles', 'days'));
}
I worked it out. I had to use Laravel's 'search' function to find the index of the array of IDs of the articles. Then that integer matched the id of the markers.
#foreach ($articles as $article)
<!-- CREATE AN ARRAY OF IDS THEN GET THE INDEX/KEY OF THIS PARTICULAR ARTICLE ID -->
<?php $something = $articles->lists('id')
$artID = $article->id;
$key= $something->search($artID); ?>
<i class="fa fa-plus-square showMoreDetails" onclick="myClick(<?php echo $key; ?>);"></i>
#endforeach