I am using the google maps API to show the last position a form was submitted to my site. So I am pulling the lon and lat values from a php file as variables but I need the script to refresh every 5 seconds so that the maps marker updates without page reload.
Here is the google api script:
<script>
function initialize() {
var myLatlng = new google.maps.LatLng<?php
require($DOCUMENT_ROOT . "php_includes/mobile_loc.php");
?>;
var mapOptions = {
zoom: 15,
center: myLatlng
}
var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Last Scan'
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
And here is the php file:
<?php
include_once("php_includes/db_conx.php");
$sql = "SELECT * FROM patdub ORDER BY STR_TO_DATE(Timestamp, '%d/%m/%Y %H:%i:%s') DESC LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_array($query);
$lon = $row['Lon'];
$lat = $row['Lat'];
echo "($lat, $lon)";
?>
Any ideas? I've tried different AJAX methods but just can't seem to figure it out!
Edit: The line of code below is basically the bit I need to refresh every 5 seconds but without any div tags or anything because that interferes with the google api script..
<?php require($DOCUMENT_ROOT . "php_includes/mobile_loc.php"); ?>;
You want to call load the file your PHP script is in, assuming that it is in it's own file, you would do that like so and you can then update your DOM using the return from the AJAX call.
You would wrap the AJAX call in a javascript loop such as setInterval() like this:
setInterval(function() {
$.ajax({
url: "php_script.php"
}).done(function(return) {
console.log(return);
});
, 5000);
To call it every 5 seconds.
To incorportate it with your Google function (I have no knowledge of google maps so this may not be 100% accurate):
<script>
function initialize(myLatlng) {
myLatlng = myLatlng || new google.maps.LatLng<?php require($DOCUMENT_ROOT . "php_includes/mobile_loc.php");?>;
var mapOptions = {
zoom: 15,
center: myLatlng
}
var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Last Scan'
});
}
google.maps.event.addDomListener(window, 'load', initialize);
setInterval(function() {
$.ajax(function() {
url: 'php_script.php'
}.done(function(response) {
var latlong = response;
initialize(latLong)
});
}, 5000)
</script>
Related
I am trying to pass php $var to Javascript in google map script. I have address table in DB. And with controller I fetch it to view and now try to pass it in Javascript and iterate it.
But having some trouble I think my code a bit corrupted. By the way I dont have lat and lng, just addresses.
function initMap(){
var options = {
zoom:8,
center:
#foreach($address as $addr){
{!! $addr->address !!}
}
#endforeach
}
var map = new google.maps.Map(document.getElementById("map"), options);
var marker = new google.maps.Marker({
position:
#foreach($address as $addr){
{!! $addr->address !!}
}
#endforeach
map:map
});
var infoWindow = new google.maps.InfoWindow({
content:'content here'
});
marker.addListener('click', function () {
infoWindow.open(map, marker);
})
}
And Map API calling
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=MY-KEY&callback=initMap"></script>
controller
public function index()
{
$address = DB::table("allestates")
->get();
return view("home", compact('address'));
}
Address column in DB:
I see a few things that could be causing the issue
Try this:
function initMap(){
var options = {
zoom:8,
center:
'{!! $address[0]->address !!}'
}
var map = new google.maps.Map(document.getElementById("map"), options);
var marker = new google.maps.Marker({
position:
#foreach($address as $addr)
'{!! $addr->address !!}'
#endforeach
map:map
});
var infoWindow = new google.maps.InfoWindow({
content:'content here'
});
marker.addListener('click', function () {
infoWindow.open(map, marker);
})
}
So first of all the #foreach (...) does not use { or }
Second you want to output any information that is not only numeric inside of quotes
Hope this helps
I'm creating a flask app and try to fetch coordinates from mysql DB, the database has latitude and longitude infomation, I'd like to show all of markers on the page with the lat/lng and tend to using js to add markers, don't know why it doesn't work. Any helps appreciated.
using flask sqlalchemy to get lat/lng info
<script>
$(document).ready(function () {
function initMap() {
var latlng = {lat: -37.8253632, lng: 144.1404107}; // THIS IS CENTER OF THE MAP
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: latlng
});
google.maps.event.addListenerOnce(map, 'tilesloaded', addMarkers);
function addMarkers() {
{% for CarD in page_data %}
var point = {lat: {{ CarD.lat }}, lng: {{ CarD.lng }} };
var marker = new google.maps.Marker({
position: point,
map: map,
title: '!'
});
{% endfor %}
marker['infowindow'] = new google.maps.InfoWindow({
content: '<div id="content" style="text-align: center"></div>'
}); // info of the point
}
}
});
</script>
Your jinja templates are processed on the server side so putting the python variables in javascript only works if the js is in your template (as in you have the html and js in the same .html file). Additionally, i would discourage you from mixing the code. I would recommend you make an ajax call and receive a json response with your points. In flask you can do something like this
#app.route('/api/coordinates)
def coordinates():
addresses = session.query(Coordinates)#however you query your db
all_coods = [] # initialize a list to store your addresses
for add in addresses:
address_details = {
"lat": add.lat,
"lng": add.lng,
"title": add.title}
all_coods.append(address_details)
return jsonify({'cordinates': all_coods})
then in your javascript you can call this endpoint then process the json object (I like to use fetch for my ajax calls)
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 16,
center: new google.maps.LatLng(-33.91722, 151.23064),
mapTypeId: 'roadmap'
});
//variable to hold your endpoint
var coodAddresses = 'https://yoursite.com/api/coordinates';
//an array to hold your cordinates
var locations = [];
//Using fetch to process the ajax call
// if you use fetch, besure to include the source below this line in your template
//<script src="https://cdnjs.cloudflare.com/ajax/libs/fetch/2.0.3/fetch.js"></script>
fetch(coodAddresses)
.then(function(response) {
return response.text();
}).then(function(body) {
var obj = JSON.parse(body);
var myAdd = {};
var addresses = obj.cordinates;
var l = addresses.length;
for (i = 0; i < l; i++) {
myAdd = {
position: {
lat: parseFloat(obj.cordinates[i].lat),
lng: parseFloat(obj.cordinates[i].lng)
},
title: obj.cordinates[i].title,
};
locations.push(myAdd);
}
locations.forEach(function(feature) {
var marker = new google.maps.Marker({
position: feature.position,
title: feature.title,
map: map
});
});
}).catch(function() {
// if the ajax call fails display an error in an info window
var pos = {
lat: lat,
lng: lng
};
infoWindow.setMap(map);
infoWindow.setPosition(pos);
infoWindow.setContent('An error occurred, we are unable to retreive cordinates.');
});
}
I hope you find this useful. If your points are not near each other, you may need to make sure the bounds include all of them
I am traying to show a google map in my main page. This map is generated by this function:
function addressCode(id,concatenadoAMostrarEnMapa) {
var geocoder;
var map;
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-35.397, -60.644);
var mapOptions = {
zoom: 5,
center: latlng
}
map = new google.maps.Map(document.getElementById(id), mapOptions);
var address = concatenadoAMostrarEnMapa;
geocoder.geocode( {
'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
google.maps.event.addDomListener(window, 'load',addressCode);
}
This function is defined in the main page. Then using ajax, I call the php file take_publications, in this file I print the following code:
$comillas='"' ;
echo " <div id='$mapa'";
echo "onload='addressCode('$mapa','$concatenadoAMostrarEnMapa')' style='position:relative; width:400px; height:400px;'> </div>";
echo "<script >addressCode('$mapa','$concatenadoAMostrarEnMapa');";
echo "setInterval(";
echo $comillas."addressCode('$mapa','$concatenadoAMostrarEnMapa')".$comillas;
echo ", 10000 );
</script >";
$mapa is a string with the id of the tag, this variable is used as argument in the function addressCode. $concatenadoAMostrarEnMapa is the address to use as argument in the function addressCode.
The problem is that the map is not loading, or rather, the script printed from the php file by ajax is not being executed.
Any idea what is happening?
Thanks in advance!
First of all, a div element doesn't have onload events.
If you really want your script to be executed on load, add your call of addressCode in a window.onload event handler, like this :
window.onload = function(){
//do anything here
};
Then, concerning the use of setInterval, if you don't need IE < 10 users to see your website, you can do :
setInterval(addressCode, 1000, "#yourmap", "nohablospanishenoughtounderstandthat");
Otherwise, you should do :
setInterval(function(){ addressCode("#yourmap","blabla"); }, 1000);
(Note that I don't support the use of setInterval, you better use setTimeout)
Finally, stop using the register_globals helper. It will never help you. Like never ever.
"<div id='$mapa'"
Should be :
"div id='".$mapa."'"
So after all, your code should look like this :
echo "<div id='".$mapa."'";
echo "style='position:relative; width:400px; height:400px;'></div>";
echo "<script>";
echo "window.onload = function(){ ";
echo "addressCode('".$mapa."','".$concatenadoAMostrarEnMapa."');";
echo "setInterval(";
echo "addressCode, 1000, '".$mapa."','".$concatenadoAMostrarEnMapa."'";
echo ");";
echo "};";
echo "</script >";
I dont have the exact answer but you can use this code for ur website..
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script>
function initialize() {
var map_canvas = document.getElementById('map_canvas');
var map_options = {
center: new google.maps.LatLng(24.376202, 92.163641),
zoom: 18,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(map_canvas, map_options)
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<div id="map_canvas"></div>
After have been searching all night, I found the solution. I had to evaluate all scritps brought by ajax, because i was inserting new scritps but the page had already loaded all its content.
Thanks!
I can pull this information from my MySQL table and display what I need to but I would like some help on how to refresh this data every 5 seconds or so with the current code that I have.
There isn't much data to show, just like 5 or 8 markers at any given time. I have included my current code that I use to pull the data. I am sort of OK with PHP/MySQL but very new to Google Maps.
<script type='text/javascript'>
//This javascript will load when the page loads.
jQuery(document).ready( function($){
//Initialize the Google Maps
var geocoder;
var map;
var markersArray = [];
var infos = [];
geocoder = new google.maps.Geocoder();
var myOptions = {
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
//Load the Map into the map_canvas div
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
//Initialize a variable that the auto-size the map to whatever you are plotting
var bounds = new google.maps.LatLngBounds();
//Initialize the encoded string
var encodedString;
//Initialize the array that will hold the contents of the split string
var stringArray = [];
//Get the value of the encoded string from the hidden input
encodedString = document.getElementById("encodedString").value;
//Split the encoded string into an array the separates each location
stringArray = encodedString.split("****");
var x;
for (x = 0; x < stringArray.length; x = x + 1)
{
var addressDetails = [];
var marker;
//Separate each field
addressDetails = stringArray[x].split("&&&");
//Load the lat, long data
var lat = new google.maps.LatLng(addressDetails[1], addressDetails[2]);
var image = new google.maps.MarkerImage(addressDetails[3]);
//Create a new marker and info window
var marker = new google.maps.Marker({
map: map,
icon: image,
position: lat,
content: addressDetails[0]
});
//Pushing the markers into an array so that it's easier to manage them
markersArray.push(marker);
google.maps.event.addListener( marker, 'click', function () {
closeInfos();
var info = new google.maps.InfoWindow({content: this.content});
//On click the map will load the info window
info.open(map,this);
infos[0]=info;
});
//Extends the boundaries of the map to include this new location
bounds.extend(lat);
}
//Takes all the lat, longs in the bounds variable and autosizes the map
map.fitBounds(bounds);
//Manages the info windows
function closeInfos(){
if(infos.length > 0){
infos[0].set("marker",null);
infos[0].close();
infos.length = 0;
}
}
});
</script>
</head>
<body>
<div id='input'>
<?php
//Initialize your first couple variables
$encodedString = ""; //This is the string that will hold all your location data
$x = 0; //This is a trigger to keep the string tidy
//Now we do a simple query to the database
// DB INFO CONNECTION IS HERE AND WORKS
$result = mysql_query("SELECT * FROM `ulocation` WHERE `ul_lat`!='' AND `ul_long`!='' AND `ul_onduty`='1'",$db1);
//Multiple rows are returned
while ($row = mysql_fetch_array($result, MYSQL_NUM))
{
//This is to keep an empty first or last line from forming, when the string is split
if ( $x == 0 )
{
$separator = "";
}
else
{
//Each row in the database is separated in the string by four *'s
$separator = "****";
}
$status='0';
$cadd = sql::getval('cal_address', 'call', "WHERE `cal_id`='$row[14]'");
$num = sql::getval('cal_num', 'call', "WHERE `cal_id`='$row[14]'");
$pcond = sql::getval('cal_pcond', 'call', "WHERE `cal_id`='$row[14]'");
$list="$num $cadd";
//Saving to the String, each variable is separated by three &'s
$encodedString = $encodedString.$separator.
"<table border=0 width='350' height='20' class='maincolm' cellpadding=0 cellspacing=0><td align=left valign=top><h2></h2></td><tr><td width=100%><font size=3 face=arial><p><b>".$row[2].
"</b>".
"<br>Address: $list".
"<br>Call Type: $pcond".
"<br><br>Lat: ".$row[5].
"<br>Long: ".$row[6].
"</td></table>".
"</p>&&&".$row[5]."&&&".$row[6]."&&&".$row[8]."&&&".$row[14];
$x = $x + 1;
}
?>
<input type="hidden" id="encodedString" name="encodedString" value="<?php echo $encodedString; ?>" />
<? echo "<body oncontextmenu=\"return false\" style=\"overflow: hidden; \" topmargin=0 leftmargin=0 rightmargin=0 bottommargin=0>";
<div id=\"map_canvas\"></div>
</body>
</html>";
?>
setInterval(function() {
$.ajax({ url: '/my/site',
data: {action: 'test'},
type: 'post',
success: function(output) {
// change the DOM with your new output info
}
});
}, 300000);
This will run an ajax call to any page you want, with any post data you want every 5 minutes.
FOR MORE CLARITY:
Let's say we have a PHP page called refreshComments.php that does this:
$result = mysql_query("SELECT * FROM `comments` WHERE `articleId` = $_POST['articleId']");
while($data = mysql_fetch_array($result)) {
$output[] = $data;
}
echo json_encode($output);
What this is doing is doing that simple query, and printing it out in a JSON object
In our Javascript, we have a page called scripts.js that does this:
setInterval(function() {
$.ajax({ url: 'refreshComments.php',
data: {articleId: '2'},
type: 'post',
success: function(output) {
// dynamically append new comments
console.log(output); // this just logs is
}
});
}, 300000);
What is this JS file doing? On an interval of 300000 milliseconds (or 5 minutes), it sends an ajax request to refreshComments.php. refreshComments.php responds with a JSON of our new data, and in the success() function, we use that new data.
I am looking for a way to add markers on to a map which I have created in a web page... Here is the code for the page...
<link href='//api.tiles.mapbox.com/mapbox.js/v1.3.1/mapbox.css' rel='stylesheet' />
<script src='//api.tiles.mapbox.com/mapbox.js/v1.3.1/mapbox.js'></script>
<style>
#map {
width: 100%;
height: 600px;
}
</style>
<div id='map' />
<script type='text/javascript'>
var map = L.mapbox.map('map', '[mapname]')
</script>
This renders the map from mapbox - but I cannot figure out how to write a web service to provide the markers. This data is stored in a table in a SQL database.
I understand that I can load a GeoJSON file with the data in - but I am unsure on how to create this file - and how it differs from regular JSON - any help would be grateful!
Thanks
I don't know GeoJSON, but this is how you handle it using the Google Maps v3 API:
For one marker:
lng = (4.502384184313996, 4.461185453845246);
lat = (51.011527400014664, 51.02974935275779);
cur_loc = new google.maps.LatLng(lat, lng);
var marker = new google.maps.Marker({
position: cur_loc, //To be defined with LatLng variable type
draggable: false,
animation: google.maps.Animation.DROP,
icon: image
});
// To add the marker to the map, call setMap();
marker.setMap(map);
For multiple markers retrieved from MySQL (Ajax):
google.maps.event.addListener(map, 'idle', function () {
var bounds = map.getBounds();
var ne_lat = bounds.getNorthEast().lat();
var ne_lng = bounds.getNorthEast().lng();
var sw_lat = bounds.getSouthWest().lat();
var sw_lng = bounds.getSouthWest().lng();
// Call you server with ajax passing it the bounds
$.ajax({
type: "GET",
url: "http://www.zwoop.be/develop/home/bars/bars_get_markers.php",
data: {
'ne_lat': ne_lat,
'ne_lng': ne_lng,
'sw_lat': sw_lat,
'sw_lng': sw_lng
},
datatype: "json",
success: function(data){
if(data){
// In the ajax callback delete the current markers and add new markers
function clearOverlays() {
for (var i = 0; i < array_markers.length; i++ ){
array_markers[i].setMap(null);
}
array_markers = [];
};
clearOverlays();
//parse the returned json obect
//Create a marker for each of the returned objects
var obj = $.parseJSON(data);
$.each(obj, function(index,el) {
var bar_position = new google.maps.LatLng(el.lat, el.lng);
image_bar = "http://www.sherv.net/cm/emoticons/drink/whiskey-smiley-emoticon.gif";
var marker = new google.maps.Marker({
position: bar_position,
map: map,
icon: image_bar
});
//Add info window. With HTML, the text format can be edited.
google.maps.event.addListener(marker, 'click', function() {
if (infowindow){
infowindow.close();
};
content = "<div id='infowindow_container'><h3><a class='profile_name_bar' href='#' id='" + el.profile_id + "'>"+el.profile_name+"</a></h3></div>";
infowindow = new google.maps.InfoWindow({
content: content
});
infowindow.open(map,marker);
});
array_markers.push(marker);
});
//Place the markers on the map
function setAllMap(map) {
for (var i = 0; i < array_markers.length; i++) {
array_markers[i].setMap(map);
}
}
setAllMap(map);
//marker clusterer
var zoom = 17;
var size = size ==-1?null:size;
var style = style ==-1?null:style;
var markerCluster = new MarkerClusterer(map, array_markers,{maxZoom:zoom,gridSize:size});
}
},
error: function (xhr, ajaxOptions, error) {
alert(error);
}
})
});
This code looks at the viewport of the map and loads the markers dynamically. When you zoom / pan, the code will query the database: the LatLng coordinates of the map bounds are sent to the server and the marker coordindates that are found in the database are returned from the Ajax call. The marker coordinates are loaded into an array at the client and written on the map.
I used the marker clusterer to avoid crowded markers.
I hope this helps. I don't know the benefits of the plugin that you are using though.
I'm doing something similar, this is where I'm up to.
I use PHP to get the coordinates from the MySQL database and return something like this:
var geoJson = [
{
type: 'Feature',
"geometry": { "type": "Point", "coordinates": [-77.03, 38.90]},
"properties": {}
},
{
type: 'Feature',
"geometry": { "type": "Point", "coordinates": [-64.567, 32.483]},
"properties": {}
}
];
The PHP file looks something like this:
<?php
// Connect
$link = mysqli_connect("[host]","[username]","[password]","[database-name]") or die("Error " . mysqli_error($link));
// Get the coordinates of the places
$query = "SELECT * FROM `places`";
$places = $link->query($query);
var geoJson = [<?php
// Loop through places and plot them on map
// This is just building the JSON string
$i = 1;
while($venue = $venues->fetch_assoc()):
if($i > 1){ echo ","; } ?>
{
type: 'Feature',
"geometry": { "type": "Point", "coordinates": [<?php echo $venue['lon']; ?>, <?php echo $venue['lat']; ?>]},
"properties": {}
}
<?php $i++; ?>
<?php endwhile; ?>
];
map.markerLayer.setGeoJSON(geoJson);
Note - This PHP is inside the Javascript that is making the map.
Like I said its early days for me as well. The code above works, but its just as far as I've got so far. The next thing I'm going to look at is JavaScript templates and using them to pull in the data that way. I have a feeling that will be a better way but I'm not sure. Anyway maybe that's useful to you, let me know if you get any further with it :)