I am designing a system based on Google Maps and GPS. I am receiving the GPS information in my server every 10 seconds, and using a Java program it stores the latitude and longitude in a mysql database. Also, I'm making a website with google maps with the idea of tracking the device in real time.
The problem I'm having is that I need to query the mysql table every 10 seconds to retrieve the latitude+longitude, and the only way I have found so far is calling the php code over and over again, meaning with this:
<script>
setInterval(function(){
document.getElementById('google-map').contentDocument.location.reload(true);
},10000);
</script>
<iframe height="540" frameborder="0" scrolling="no" marginheight="10" marginwidth="0" width="100%" name="google-map" id="google-map"
src="google-map.php">
</iframe>
I am calling the php code under the name of google-map.php:
<?php
include_once("includes/checksession.php");
include_once("dbconn/dbconn.php");
$db = new runQuery();
$db->Dbconn(); //until now I just connect to my DB
$user_id = #$_SESSION['user_id'];
$sel_qry = "select * from Historico where Gps_Gpscol=\"$user_id\" order by Fecha desc limit 1";
$res_qry = mysql_query($sel_qry);
$num = mysql_num_rows($res_qry);
$row = mysql_fetch_assoc($res_qry);
$latitude = $row['Latitud'];
$lat_array = explode('.',$latitude);
$lat_deg = $lat_array[0];
$lat_array_new = explode(' ',$lat_array[0]);
$lat_deg = $lat_array_new[0];
$longitude = explode(".",$row['Longitud']);
$long_1 = explode(" ",$longitude[0]);
$long_deg = $long_1[0];
$long_min = $long_1[1];
$long_sec = $longitude[1];
$lat_new = $lat_deg.'.'.$lat_min.$lat_sec;
$long_new = $long_deg.'.'.$long_min.$long_sec;
[NOT RELEVANT CODE.. SUPRESED]
$nombre_format_lat = number_format($lat, 6, '.', ' ');
$nombre_format_long = number_format($long, 6, '.', ' ');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Kiwi</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script type="text/javascript">
function LoadGmaps() {
var myLatlng = new google.maps.LatLng('-<?php echo $nombre_format_lat; ?>', '-<?php echo $nombre_format_long; ?>');
var myOptions = {
zoom: 17,
center: myLatlng,
disableDefaultUI: true,
panControl: true,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.DEFAULT
},
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR
},
streetViewControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var image = {
url: 'img/kiwi.png',
scaledSize: new google.maps.Size(30,30)
}
var map = new google.maps.Map(document.getElementById("MyGmaps"), myOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: '-<?php echo $row['Latitud']; ?> -<?php echo $row['Longitud']; ?>',
icon: image,
draggable: true
});
var myLatlng2 = new google.maps.LatLng('-34.607900','-58.426182');
var marker = new google.maps.Marker({
position: myLatlng2,
map: map,
title:"Pappo",
icon: image
});
}
</script>
</head>
<body onload="LoadGmaps()" onunload="GUnload()">
<!-- Maps DIV : you can move the code below to where you want the maps to be displayed -->
<div id="MyGmaps" style="width:100%;height:550px;border:1px solid #CECECE;"></div>
<!-- End of Maps DIV -->
</body>
</html>
The code is very long but it just query the database, extract the latitude and longitude, and converts it to a format I can actually use for google maps. Finally, the only variables I care are:
$nombre_format_lat and $nombre_format_long
But this way, the whole map is going to be reloaded every 10 seconds, which is very uncomfortable and I am planning to sell a service based on this website. I need to retrieve the latitude and longitude every 10 seconds but only reloading the marker! I tried to write the setInterval function inside the HTML code and calling the $nombre_format_lat and $nombre_format_long variables, but since I'm not fetching the database, those values will always be the same.
Any help would be much appreciated!
Thanks in advance.
Related
I currently have realtime analytics php api. It has this entity named $resulting. If I do print_r($resulting); it returns for example (if only 1 user is online):
Array ( [0] => Array ( [0] => Arnhem [1] => 5.898730 [2] => 51.985104 [3] => Chrome [4] => DESKTOP [5] => / [6] => 1 ) )
Now, later on in the same file, I have the google maps javascript api.
It has markers in the form of:
var markers = [
{
coords:{lat:52.0907,lng:5.1214},
content:'<h1>Utrecht</h1>'
},
{
coords:{lat:52.0907,lng:5},
content:'<h1>Links</h1>'
},
{
coords:{lat:52.0907,lng:6},
content:'<h1>Rechts</h1>'
}
];
As placeholder for now.
What I want to do, is have in the coords: section have the lat: and lng: be the appropriate values from $resulting.
Also, I want to have as many markers as there are users online.
Now, I have tried everything I can think of, but I can't get it to work.
I have tried for example:
const results = <? php echo json_encode($resulting); ?>;
let markers = [];
for(let i = 0; i < results.length; i++) {
markers[i] = {
coords: {
lat: results[1],
lng: results[2]
}
};
}
but then the maps won't load anymore.
I have tried looping, foreach, trying to get the lat: and lng: to update with the values returned by $resulting, but whatever I do it simply won't work.
Can anybody help me and get this working?
Thanks.
edit:
adding the index.php file as requested:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="jquery.json-2.4.min.js"></script>
<title>My Google Map</title>
<style>
#map{
height: 400px;
width:400px;
}
</style>
</head>
<body>
<h1>My Google Map</h1>
<div id="map"></div>
<?php
require_once __DIR__ . '/../google/vendor/autoload.php';
$analytics = initializeAnalytics();
function initializeAnalytics()
{
// Creates and returns the Analytics Reporting service object.
// Use the developers console and download your service account
// credentials in JSON format. Place them in this directory or
// change the key file location if necessary.
$KEY_FILE_LOCATION = __DIR__ . 'MY KEY FILE LOCATION';
// Create and configure a new client object.
$client = new Google_Client();
$client->setApplicationName("Hello Analytics Reporting");
$client->setAuthConfig($KEY_FILE_LOCATION);
$client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
$analytics = new Google_Service_Analytics($client);
return $analytics;
}
/**
* 1.Create and Execute a Real Time Report
* An application can request real-time data by calling the get method on the Analytics service object.
* The method requires an ids parameter which specifies from which view (profile) to retrieve data.
* For example, the following code requests real-time data for view (profile) ID 56789.
*/
$optParams = array(
'dimensions' => 'rt:city, rt:longitude, rt:latitude, rt:browser, rt:deviceCategory, rt:pagePath');
try {
$resultsrealtime = $analytics->data_realtime->get(
'ga:MY GOOGLE CLIENT ID',
'rt:activeUsers',
$optParams);
// Success.
} catch (apiServiceException $e) {
// Handle API service exceptions.
$error = $e->getMessage();
}
/**
* 2. Print out the Real-Time Data
* The components of the report can be printed out as follows:
*/
$resulting = $resultsrealtime->getRows();
function test() {
if(count($resulting == false)){
return;
}
else if(count($resulting) > 0){
foreach ($resulting as $resultingTwo => $resultingThree) {
foreach ($resultingThree as $resultingFour){
echo $resultingFour.'<br />';
}
}
} else {
echo 'No visitors';
}
}
?>
<script>
// Map options
function initMap(){
var options = {
zoom:7,
center:{lat:52.0907, lng:5.1214}
}
// New map
var map = new google.maps.Map(document.getElementById('map'), options);
// Array of markers
var markers = [
{
coords:{lat:52.0907,lng:5.1214},
iconImage:'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png',
content:'<h1>Utrecht</h1>'
},
{
coords:{lat:52.0907,lng:5},
content:'<h1>Links</h1>'
},
{
coords:{lat:52.0907,lng:6},
content:'<h1>Rechts</h1>'
}
];
// Loop through markers
for(var i = 0; i < markers.length; i++){
// add Marker
addMarker(markers[i]);
}
// Add Marker Function
function addMarker(props){
var marker = new google.maps.Marker({
position: props.coords,
map:map,
//icon:props.iconImage
});
// Check for custom icon
if(props.iconImage){
// Set icon image
marker.setIcon(props.iconImage);
}
// Check for content
if(props.content){
// Set content
// Info Window
var infoWindow = new google.maps.InfoWindow({
content:props.content
});
marker.addListener('mouseover', function(){
infoWindow.open(map, marker);
// Reset Info Window
setTimeout(function(){
infoWindow.open()
}, 500);
}, false);
}
}
}
</script>
<div id="data"><p><?php $test = json_encode($resulting); print_r($test);?></p></div>
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js">
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBuvHNJq4R6v_62R03EVG0n8UdIzXTEiI4&callback=initMap">
</script>
</body>
</html>
Also, what the json_encode returns with 2 users online:
[["Arnhem","5.898730","51.985104","Chrome","DESKTOP","\/","1"],["Eindhoven","5.469722","51.441643","Chrome","MOBILE","\/","1"]]
You should also assign the map object to the marker (assuming your map object is named map )
for(let i = 0; i < results.length; i++) {
markers[i] = {
coords: {
lat: results[1],
lng: results[2]
},
map: map
};
}
To help you identify the issue, it would be useful to see the rest of your javascript code for the map api, as well as the array when there's more than one user after running it though json_encode(). That said, try the following:
const results = <? php echo json_encode($resulting); ?>;
for(let i = 0; i < results.length; i++) {
let marker = new google.maps.Marker({
position: {lat: results[1], lng: results[2]},
content: '<h1>' + results[0] + </h1>,
map: map
});
}
Edit:
I don't have Composer installed in the directory I tested your code in, and I haven't worked much with the Google realtime API, but the following javascript will work given the output you listed for $resulting. You'll have to tweak things depending on where your custom icons are coming from, but that should be pretty straightforward.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="jquery.json-2.4.min.js"></script>
<title>My Google Map</title>
<style>
#map{
height: 400px;
width:400px;
}
</style>
</head>
<body>
<h1>My Google Map</h1>
<div id="map"></div>
<?php $resulting = array(array("Arnhem","5.898730","51.985104","Chrome","DESKTOP","\/","1"), array("Eindhoven","5.469722","51.441643","Chrome","MOBILE","\/","1")); ?>
<script>
const resultingArr = <?php echo json_encode($resulting); ?>;
function initMap() {
var options = {
zoom: 7,
center: {
lat: 52.0907,
lng: 5.1214
}
}
var map = new google.maps.Map(document.getElementById('map'), options);
function mapMarkers(props) {
const marker = new google.maps.Marker({
position: props.coords,
map: map,
icon: props.iconImage
});
const infoWindow = new google.maps.InfoWindow({
content: props.content
});
marker.addListener('mouseover', function() {
infoWindow.open(map, marker);
});
marker.addListener('mouseout', function() {
infoWindow.close();
});
}
for (let i = 0; i < resultingArr.length; i++) {
mapMarkers({
coords: {
lat: parseFloat(resultingArr[i][2]),
lng: parseFloat(resultingArr[i][1])
},
content: '<h3>' + resultingArr[i][0] + '</h3>'
})
}
};
</script>
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js">
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBuvHNJq4R6v_62R03EVG0n8UdIzXTEiI4&callback=initMap">
</script>
</body>
</html>
Hope this helps!
I'm using google maps API to make a map that retrieves data from the database and shows the corresponding markers on the map. I did this by following these instructions: https://developers.google.com/maps/articles/phpsqlajax_v3
What I'm now trying to do is create a page (called add_marker.php) that has a draggable marker so that the user can then add the new marker to the database based on the coordinates. I want to be able to see the other markers when I'm on this page. I also include the map code in all the pages so I don't want it to change drastically just for this page, so my approach is the following: Make the draggable marker invisible in all the pages except for the add_marker page by setting the icon setting to an empty string " ". Now the problem is, I can't change the icon's image so I can see it in the particular page I want it visible. I've searched quite a bit here in stackoverflow and found some solution, but none of these worked.
The error that I get is: add_marker.php:9 Uncaught Reference Error: drag_marker is not defined
(Even though I've made the marker variable global)
The code is the following:
map_code.php (This is the page that I made with the help of the link and is almost identical to that code except for some variable names. It's included in the files that use the map)
Any help would be greatly appreciated
<!DOCTYPE html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>PHP/MySQL & Google Maps Example</title>
<script src="https://maps.googleapis.com/maps/api/js?key=MY_KEY"
type="text/javascript"></script>
<script type="text/javascript">
var drag_marker;
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(37.511769, 22.371699),
zoom: 13,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
downloadUrl("phpsqlajax_genxml.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var content = markers[i].getAttribute("content");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("latitude")),
parseFloat(markers[i].getAttribute("longitude")));
var content = markers[i].getAttribute("content");
var icon = 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png';
var marker = new google.maps.Marker({
map: map,
position: point,
icon: 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png'
});
bindInfoWindow(marker, map, infoWindow, content, name);
}
});
*var uluru = {lat: 37.52, lng: 22.37};
drag_marker = new google.maps.Marker({
icon: " ",
draggable: true,
position: uluru,
map: map
});*
}
function SelectElement(valueToSelect)
{
var element = document.getElementById("markerList");
element.value = valueToSelect;
}
function bindInfoWindow(marker, map, infoWindow, html, name) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
infoWindow.setContent("<p>" + name + "<br />" +
html + "<br />");
SelectElement(name);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
</script>
</head>
<body onload="load()">
<div id="map" style="width: 99.5%; height: 40%"></div>
</body>
</html>
add_marker.php:
<html>
<head>
<title>My website</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="style.css" />
<script type="text/javascript">
drag_marker.setIcon("http://maps.google.com/mapfiles/ms/icons/red-dot.png");
</script>';
</head>
<body>
<div id="container">
<div id="header">
<h1><img src="logo.png" align="center" alt="logo" style="width:300px;height:60px;"><img src="gavlab.png" align="right" alt="logo" style="width:200px;height:55px;"></h1>
</div>
<div id="content">
<div id="nav">
<h3>Πλοήγηση</h3>
<ul id="menu">
<li>Homepage</li>
<li align="left">Map</li>
<li>Admin log-in</li>
<li>info</li>
<li>Contact</li>
</ul>
</div>
<div id="main">
<h6 align="center">Map</h6>
<?php include("map_code.php"); ?>
<div align="center" id="admin_menu">
<?php
error_reporting(E_ALL & ~E_NOTICE ^ E_DEPRECATED ^ E_WARNING );
//http://www.clker.com/cliparts/e/3/F/I/0/A/google-maps-marker-for-residencelamontagne-hi.png
// icon:"http://maps.google.com/mapfiles/ms/icons/red-dot.png",
SESSION_START();
if($_SESSION['username'] == "admin"||$_SESSION['username'] == "username"){
echo '<p align="center" style="color:#8A2908"> Welcome εδώ.</p>';
$con= mysql_connect('localhost','root','');
mysql_set_charset('utf8');
mysql_select_db('qr code');
mysql_query("SET character_set_results = 'utf8', character_set_client = 'utf8', character_set_connection = 'utf8', character_set_database = 'utf8', character_set_server = 'utf8'", $con);
$sql="SELECT * FROM array1";
$records=mysql_query($sql);
echo '<form id="main_form" name = "add_new_marker" action="marker_info.php" method="post">';
'</form>';
}
else echo '<p align="center" style="color:#8A2908">Please log in εδώ.</p>';
?>
</div>
</div>
</div>
<div id="footer">
Copyright © 2016 Name Here
</div>
</div>
</body>
</html>
You are attempting to use the drag_marker variable before it is defined (and probably also before it is initialized, look at the HTML/JavaScript rendered in the browser).
To deal with the timing issue, try:
google.maps.event.addDomListener(window, 'load', function() {
drag_marker.setIcon("http://maps.google.com/mapfiles/ms/icons/red-dot.png");
}):
I want to display multiple tags on my google map based on the location from my database. I am using PHP and javascript for my map. I am at lost for the moment on how I will be able to show all the locations from my database. Could anyone please help me? I would really appreciate it. Thanks in advance!
below is my current code for my map:
<?php
$hostname = 'localhost';
$dbname = 'db'; // Your database name.
$username = 'root'; // Your database username.
$password = ''; // Your database password. If your database has no password, leave it empty.
mysql_connect("$hostname", "$username", "$password") or DIE("Connection to host is failed, perhaps the service is down!");
mysql_select_db("$dbname") or DIE("database not available");
$loc = "N1433.704483,E12100.012501";
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>DLTI Locator</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
</head>
<body>
<div id="map" style="width: 500px; height: 500px;"></div>
<script type="text/javascript">
var locations = [
['Bondi Beach', latitude,longitude ],
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(14.5833, 120.9667),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
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>
</body>
</html>
try this tutorial.. i used it to get markers from my database.. you too could do the same..
https://developers.google.com/maps/articles/phpsqlajax_v3
I am using google markers on my webpage.The latitude,longitude,name and detail are fetched from database using php page and then m using it on jquery using $.post method.
<?php
//Basic environment setup (error handling and logging, cookies/sessions, php directives etc)
require_once $_SERVER['DOCUMENT_ROOT'] . '/../Config/path_config.php';
require_once C_PATH_UTILITY_MANAGER_PAGESETUP;
Page_Setup_Manager::setDefaultPageSettings();
require_once C_DIR_UTILITY_EVENTS_DATAACCESS;
$eventsdats=Eventsdata::getevents();
$temp=array();
foreach($eventsdats as $singlemapevent)
{
array_push($temp,array($singlemapevent['ename'],
(floatval($singlemapevent['latitude'])),
(floatval($singlemapevent['longitude'])),
($singlemapevent['edate']),
($singlemapevent['etime']),
($singlemapevent['edetail'])
));
}
echo json_encode($temp);
//Result[["Second Event",19.0554748,72.8497017,"17-12-2012","17:57 ","This is the
social detail;"],["Demo Event",19.2097381,72.8737017,"08-12- 2012","09:34 ","This event
was held in bhayander by ganesh mandhre"],]
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
function initialize() {
markers=[];
temp=[];
final_markers=[];
$.post('maps_data.php',{},function(data){
},"json").done(function(data){
markers=(data);
$.each(data,function(index,value){
final_markers.push($.makeArray(value));
});
markers=final_markers;
});
alert(markers);
var latlng = new google.maps.LatLng(19.0554748, 72.8497017);
var settings = {
zoom: 10,
center: latlng,
visible:true,
mapTypeControl: true,
mapTypeControlOptions: {style:
google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
navigationControlOptions: {style:
google.maps.NavigationControlStyle.SMALL},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new
google.maps.Map(document.getElementById("map_canvas"), settings);
var infowindow = new google.maps.InfoWindow(), marker, i;
for (i = 0; i < markers.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(markers[i][1], markers[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
var contentString = '<div id="content">'+
'<div id="siteNotice">'+
'</div>'+
'<h1 id="firstHeading" class="firstHeading">'+markers[i][0]+'</h1>'+
'<div id="bodyContent">'+
'<p>'+markers[i][3]+'</p>'+
'<p>'+markers[i][4]+'</p>'+
'<p>'+markers[i][5]+'</p>'+
'</div>'+
'</div>';
infowindow.setContent(contentString);
infowindow.open(map, marker);
}
})(marker, i));
}
}
</script>
<title>Untitled Document</title>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:100%; height:350px"></div>
</body>
</html>
The markers are visible in firefox but not in chrome and safari..What is the error ? Am i using json incorrectly ?
When you get your json data, you have to process them in the callback. Here you display the map and marker before the ajax call is complete. Move this rendering to the done callback.
I am very new in HTML5 area, I am trying to make a program that will fetch the data from mysql with PHP and use geocode to transform from address to Latlng. it is a LBS program, and I was trying for 2 weeks, my question is I cannot put markers into the Google MAP, I did the locator corrected and map is loaded, but the marker cannot land on map, please help!! thank you, and I am really appreciate your help. if this code has any mistake or problem please give me generous advice, I am very new in this area, and I am trying to learn more in HTML5 Javascript, thank you and I am very appreciate your advice!!!
my code is here:
'enter code here`<?php
require_once 'Common/system_start.php';
$sql="select addr from tab_mem order by sn desc ";
$result= mysql_query($sql);
$data=mysql_fetch_assoc($result);
$row=mysql_num_rows($result);
$n = array();
for($i=0;$i<$rows;$i++)
{
$data=mysql_fetch_row($result);
$n[] = $data[0];
}
echo '<script type="text/javascript">';
echo var n = new Array("', join($n,'","'), '");';
echo '</script>';
?>
<code>
<pre>
<!DOCTYPE html>
<html><head><meta charset="utf-8">
<meta name="viewport" content="initial-scale=1.0,user-scalable=no"/>
<!-- Google Maps -->
<script type="text/javascript" src="http://maps.google.com/maps/api/js? `enter code here`sensor=true"></script>
<script type="text/javascript" charset="utf-8" src="cordova-1.6.0.js">
</script>
<!-- program main -->
<script type="text/javascript">
var iterator=0;
markers=n;
var a=n.length;
function load() {
var map_div = document.getElementById("map_div");
//initial locator
navigator.geolocation.watchPosition(onSuccess, onError, { frequency: 3000 `enter code here`});
// decide location
function onSuccess(position){
//fetching latlng from GPS
var latlng = new google.maps.LatLng(position.coords.latitude,
`position.coords.longitude);
// display map
var gmap = new google.maps.Map(
map_div, {
zoom:16,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
//drop the marker
function drop() {
for (var i = 0; i < a; i++) {
setTimeout(function() {
}, i * 200);
}
}
//decode address to latlng
//pass address data from PHP
for(var i in n){
var address=n;
geocoder=new google.maps.Geocoder();
geocoder.geocode({'address':address},function(results,status){
if(status==google.maps.GeocoderStatus.OK){
//alert("AAA");
address=results(i).geometry.location;
function addMarker() { markers.push(new google.maps.Marker({
postion:results(i).geometry.location,
map:gmap,
animation:google.map.animation.DROP
//iterater++;
}));
//itertor++;
}
//markerNearBy.setMap(map);
}else{
alert("Geocode was not sucessful for the following reason:"+status);
}
});
}
}
}
function onError(error) {
alert('code: '+ error.code+ '\n'
+'message: ' + error.message + '\n');
}
</script>
</head>
<body onLoad="load()">
<!-- Map Display place -->
<div id="map_div" style="width:320px; height:480px;"></div>
</body>
</html>
<code>
Your code doesn't look well-formed. You have the "addMarker" function defined inside your "for" loop. Also, it's not getting called anywhere.
Take a look at the sample code Google provides for working with markers and overlays and try to emulate it. The sample only uses one marker, but you can simply iterate through your results. You've got the right intentions by adding your Marker objects to an array, and setting your map object to the map property of the Marker, but you will need to format/restructure your code first or it will not work.
Sample code:
https://developers.google.com/maps/documentation/javascript/overlays#RemovingOverlays