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.
Related
Hello such first of all thank you for your help friends.
I would like to see if they can help me with this problem, I'm inserting routes latitude and longitude of Google Maps incluyendole a capo text input called "pathname" in my database, all very well to insert the latitude and longitude, but when you insert the "pathname" I returned in the cast of the pathname field inserccionen "[object HTMLCollection]"
What I want is to insert text or value of that input.
Below is my code to see if they can give me a hand you'll be thanked
Php Code Index.php:
<?php
$lat = "18.472848374914534";
$lng = "-69.92593261718753";
$pos = $_POST ["pos"];
$nombre_ruta = $_POST ["nombre_ruta"];
echo "
<div id='info' name='info' class='info'>".$pos."</div>
<div id='seleccion_mapa'></div>
<input type='text' name='nombre_ruta' id='nombre_ruta' placeholder='ponga aqui, el nombre de la ruta' class='Txt_SELECCIONAR' />
<input type='submit' id='enviar' name='enviar' value='CREAR RUTA' class='Txt_btn_submit2' value='CREAR RUTA'>
<br>
<div id='respuesta'></div>";
?>
js Script Ajax
<script>
$(document).ready(function(){
lat = "<?php echo $lat; ?>" ;
lng = "<?php echo $lng; ?>" ;
var map;
function initialize() {
var myLatlng = new google.maps.LatLng(lat,lng);
var mapOptions = {
zoom: 7,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("seleccion_mapa"), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
draggable:true,
animation: google.maps.Animation.DROP,
web:"Localización geográfica!",
icon: "../../../../assets/img/marker.png"
});
google.maps.event.addListener(marker, 'dragend', function(event) {
var myLatLng = event.latLng;
lat = myLatLng.lat();
lng = myLatLng.lng();
nombre_ruta = myLatLng.nombre_ruta();
document.getElementByTagId('info').innerHTML = [
lat,
lng,
nombre_ruta
].join(', ');
});
marker.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
$("#enviar").click(function() {
var url = "../../../controllers/cargar_mapa.php";
$("#respuesta").html('<img src="../../../../assets/img/loading17.gif" />');
$.ajax({
type: "POST",
url: url,
data: 'lat=' + lat + '&lng=' + lng + '&nombre_ruta=' + nombre_ruta ,
success: function(data)
{
$("#respuesta").html(data);
}
});
});
});
</script>
and database insert code
<?php
error_reporting(E_ERROR | E_WARNING | E_PARSE);
include('../../Connections/conexion_mapa_ruta.php');
$lat=strip_tags(mysqli_real_escape_string($con,$_POST['lat']));
$lng=strip_tags(mysqli_real_escape_string($con,$_POST['lng']));
$nombre_ruta=$_POST['nombre_ruta'];
$pos=$lat.",".$lng;
mysqli_query($con,"INSERT INTO ruta_transporte (Lat, Lng, Pos, nombre_ruta) values ('$lat','$lng','$pos','$nombre_ruta')");
echo "<b> Posición guardada: </b>".$nombre_ruta.",".$lat.", ".$lng;
?>
When you build your POST data client-side:
data: 'lat=' + lat + '&lng=' + lng + '&nombre_ruta=' + nombre_ruta
nombre_ruta is an object. Possibly from when it's set here?:
nombre_ruta = myLatLng.nombre_ruta();
I'm really not sure what that method is returning, you may need to debug in your browser to find out. But the point is that, whatever is in that variable, it's an object. And since you're trying to build a string from it, the string representation of an object is exactly what you see:
[object HTMLCollection]
Since you're building a string of key/value pairs, and since your server-side code expects to handle a string (by inserting it into a text column in a database), you're going to want to make sure your variable is set to a simple string value before POSTing that value.
What that string value needs to be, that's up to you. Maybe some property on the object you have? (Not sure how likely that is, I'm still very unclear on why the Google Maps API would have a nombre_ruta() method on an event property, or why that method would return an HTMLCollection object. You're probably going to have to do some more debugging, there could be more going on than what's presented in the question.)
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>
Well, I've a google map where all lat and long comes from db and it's showing on the map.
What I can do with this map:
1) I can create new point after right click on the map,
2) I can delete existing point.
Now can you plz tell me how can i update the db with new lat and long when the existing marker point is move to another place ?
you can see my live map on www.creativeartbd.com/map
Index.php page code:
<!DOCTYPE html>
<html>
<head>
<title>Google Map</title>
<script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api
/js?sensor=false"></script>
<script type="text/javascript">
$(document).ready(function() {
var mapCenter = new google.maps.LatLng(23.721869, 90.390518); //Google map
Coordinates
var map;
map_initialize(); // initialize google map
//############### Google Map Initialize ##############
function map_initialize()
{
var googleMapOptions =
{
center: mapCenter, // map center
zoom: 15, //zoom level, 0 = earth view to higher value
maxZoom: 15,
minZoom: 5,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL //zoom control size
},
scaleControl: true, // enable scale control
mapTypeId: google.maps.MapTypeId.ROADMAP // google map type
};
map = new google.maps.Map(document.getElementById("google_map"),
googleMapOptions);
//Load Markers from the XML File, Check (map_process.php)
$.get("map_process.php", function (data) {
$(data).find("marker").each(function () {
var name = $(this).attr('name');
var address = '<p>'+ $(this).attr('address') +'</p>';
var type = $(this).attr('type');
var point = new
google.maps.LatLng(parseFloat($(this).attr('lat')),parseFloat($(this).attr('lng')));
create_marker(point, name, address, false, false, false, "icons/pin_blue.png");
});
});
//Right Click to Drop a New Marker
google.maps.event.addListener(map, 'rightclick', function(event) {
//Edit form to be displayed with new marker
var EditForm = '<p><div class="marker-edit">'+
'<form action="ajax-save.php" method="POST" name="SaveMarker" id="SaveMarker">'+
'<label for="pName"><span>Place Name :</span><input type="text" name="pName"
class="save-name" placeholder="Enter Title" maxlength="40" /></label>'+
'<label for="pDesc"><span>Description :</span><textarea name="pDesc" class="save-desc"
placeholder="Enter Address" maxlength="150"></textarea></label>'+
'<label for="pType"><span>Type :</span> <select name="pType" class="save-type"><option
value="restaurant">Rastaurant</option><option value="bar">Bar</option>'+
'<option value="house">House</option></select></label>'+
'</form>'+
'</div></p><button name="save-marker" class="save-marker">Save Marker
Details</button>';
//Drop a new Marker with our Edit Form
create_marker(event.latLng, 'New Marker', EditForm, true, true, true,
"icons/pin_green.png");
});
}
//############### Create Marker Function ##############
function create_marker(MapPos, MapTitle, MapDesc, InfoOpenDefault, DragAble,
Removable, iconPath)
{
//new marker
var marker = new google.maps.Marker({
position: MapPos,
map: map,
draggable:true,
animation: google.maps.Animation.DROP,
title:"Hello World!",
icon: iconPath
});
//Content structure of info Window for the Markers
var contentString = $('<div class="marker-info-win">'+
'<div class="marker-inner-win"><span class="info-content">'+
'<h1 class="marker-heading">'+MapTitle+'</h1>'+
MapDesc+
'</span><button name="remove-marker" class="remove-marker" title="Remove
Marker">Remove Marker</button>'+
'</div></div>');
//Create an infoWindow
var infowindow = new google.maps.InfoWindow();
//set the content of infoWindow
infowindow.setContent(contentString[0]);
//Find remove button in infoWindow
var removeBtn = contentString.find('button.remove-marker')[0];
var saveBtn = contentString.find('button.save-marker')[0];
//add click listner to remove marker button
google.maps.event.addDomListener(removeBtn, "click", function(event) {
remove_marker(marker);
});
if(typeof saveBtn !== 'undefined') //continue only when save button is present
{
//add click listner to save marker button
google.maps.event.addDomListener(saveBtn, "click", function(event)
{
var mReplace = contentString.find('span.info-content');
//html to be replaced after success
var mName = contentString.find('input.save-name')[0].value; //name input field value
var mDesc = contentString.find('textarea.save-desc')[0].value; //description input
field value
var mType = contentString.find('select.save-type')[0].value; //type of marker
if(mName =='' || mDesc =='')
{
alert("Please enter Name and Description!");
}else{
save_marker(marker, mName, mDesc, mType,
mReplace); //call save marker function
}
});
}
//add click listner to save marker button
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker); // click on marker opens info window
});
if(InfoOpenDefault) //whether info window should be open by default
{
infowindow.open(map,marker);
}
}
//############### Remove Marker Function ##############
function remove_marker(Marker)
{
/* determine whether marker is draggable
new markers are draggable and saved markers are fixed */
//Remove saved marker from DB and map using jQuery Ajax
var mLatLang = Marker.getPosition().toUrlValue(); //get marker position
var myData = {del : 'true', latlang : mLatLang}; //post variables
$.ajax({
type: "POST",
url: "map_process.php",
data: myData,
success:function(data){
Marker.setMap(null);
alert(data);
},
error:function (xhr, ajaxOptions, thrownError){
alert(thrownError); //throw any errors
}
});
}
//############### Save Marker Function ##############
function save_marker(Marker, mName, mAddress, mType, replaceWin)
{
//Save new marker using jQuery Ajax
var mLatLang = Marker.getPosition().toUrlValue(); //get marker position
var myData = {name : mName, address : mAddress, latlang : mLatLang, type :
mType }; //post variables
console.log(replaceWin);
$.ajax({
type: "POST",
url: "map_process.php",
data: myData,
success:function(data){
replaceWin.html(data); //replace info window with new html
Marker.setDraggable(true); //set marker to fixed
Marker.setIcon('icons/pin_blue.png'); //replace icon
},
error:function (xhr, ajaxOptions, thrownError){
alert(thrownError); //throw any errors
}
});
}
});
</script>
</head>
<body>
<h1 class="heading">My Google Map</h1>
<div align="center">Right Click to Drop a New Marker</div>
<div id="google_map"></div>
</body>
</html>
Map_process.php code
// database settings
$db_username = 'username';
$db_password = 'pass';
$db_name = 'db';
$db_host = 'my host';
//mysqli
$mysqli = new mysqli($db_host, $db_username, $db_password, $db_name);
if (mysqli_connect_errno())
{
header('HTTP/1.1 500 Error: Could not connect to db!');
exit();
}
################ Save & delete markers #################
if($_POST) //run only if there's a post data
{
//make sure request is comming from Ajax
$xhr = $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest';
if (!$xhr){
header('HTTP/1.1 500 Error: Request must come from Ajax!');
exit();
}
// get marker position and split it for database
$mLatLang = explode(',',$_POST["latlang"]);
$mLat = filter_var($mLatLang[0], FILTER_VALIDATE_FLOAT);
$mLng = filter_var($mLatLang[1], FILTER_VALIDATE_FLOAT);
//Delete Marker
if(isset($_POST["del"]) && $_POST["del"]==true)
{
$results = $mysqli->query("DELETE FROM markers WHERE lat=$mLat AND lng=$mLng");
if (!$results) {
header('HTTP/1.1 500 Error: Could not delete Markers!');
exit();
}
exit("Done!");
}
$mName = filter_var($_POST["name"], FILTER_SANITIZE_STRING);
$mAddress = filter_var($_POST["address"], FILTER_SANITIZE_STRING);
$mType = filter_var($_POST["type"], FILTER_SANITIZE_STRING);
$results = $mysqli->query("INSERT INTO markers (name, address, lat, lng, type)
VALUES ('$mName','$mAddress',$mLat, $mLng, '$mType')");
if (!$results) {
header('HTTP/1.1 500 Error: Could not create marker!');
exit();
}
$output = '<h1 class="marker-heading">'.$mName.'</h1><p>'.$mAddress.'</p>';
exit($output);
}
################ Continue generating Map XML #################
//Create a new DOMDocument object
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers"); //Create new element node
$parnode = $dom->appendChild($node); //make the node show up
// Select all the rows in the markers table
$results = $mysqli->query("SELECT * FROM markers WHERE 1");
if (!$results) {
header('HTTP/1.1 500 Error: Could not get markers!');
exit();
}
//set document header to text/xml
header("Content-type: text/xml");
// Iterate through the rows, adding XML nodes for each
while($obj = $results->fetch_object())
{
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("name",$obj->name);
$newnode->setAttribute("address", $obj->address);
$newnode->setAttribute("lat", $obj->lat);
$newnode->setAttribute("lng", $obj->lng);
$newnode->setAttribute("type", $obj->type);
}
echo $dom->saveXML();
Thanks a ton for you help :)
You should add an even listener to the marker that is fired when the marker is dropped.
// adds an event listener on the marker.
// The event is fired when the marker is dropped in this case
google.maps.event.addListener(marker, 'dragend', function() {
alert('Marker dropped');
});
Don't forget to set the marker option draggable:true
Here is the doc for the methods and events for the Marker class: google.maps.Marker
And here a demo on jsFiddle
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 :)
I'm attempting to combine perl and Javascript to map IP address Lat/Long locations to a Google Map using the Google Maps API v3. What I'm getting back is in the marker, I'm getting the error: Uncaught Error: Invalid value for property <position>: 43.073052,-89.40123
My code is:
#!/usr/bin/perl -w
use CGI qw(:standard);
use CGI::Carp qw/fatalsToBrowser warningsToBrowser/;
use CGI::Session ( '-ip_match');
use SOAP::Lite;
use lib '/home/schreiber/perl5/lib/perl5';
use JSON qw(encode_json);
$session = CGI::Session->load();
$q = new CGI;
my $soap = SOAP::Lite
-> uri('http://v1.fraudlabs.com/')
-> proxy('http://v1.fraudlabs.com/ip2locationwebservice.asmx')
-> on_action(sub { join "/", "http://v1.fraudlabs.com", $_[1] });
$license = "<removed>";
#if($session->is_expired) {
# print $q->header(-cache_control=>"no-cache, no-store, must-revalidate");
# print "Your session has expired. Please login again.";
# print "<br/>Login";
#} elsif($session->is_empty) {
# print $q->header(-cache_control=>"no-cache, no-store, must-revalidate");
# print "You have not logged in";
#} else {
print $q->header(-cache_control=>"no-cache, no-store, must-revalidate");
open (IPF, "/home/access_log");
#incomingarray=<IPF>;
$i = 0;
foreach $pair(#incomingarray) {
($ip, $rest) = split(/ - - /, $pair);
$incomingarray[$i] = $ip;
chomp $ip;
$i++;
}
close (IPF);
my %hash = map { $_, 1 } #incomingarray;
my #distinctIP = keys %hash;
$j = 0;
my #iplocation;
foreach (#distinctIP) {
my $method = SOAP::Data->name('IP2Location')->attr({xmlns =>
'http://v1.fraudlabs.com/' });
my #params = SOAP::Data->name('inputdata' => \SOAP::Data->value(
SOAP::Data->name(IP=>$_),
SOAP::Data->name(LICENSE=>$license)
));
my $result = $soap->call($method => #params);
$lat = $result->valueof('//LATITUDE');
$long = $result->valueof('//LONGITUDE');
push(#iplocation, "$lat,$long");
}
my $json = encode_json(\#iplocation);
# print "Content-Type: text/html\n\n";
print '<html>
<head>
<script type="text/javascript">
function initialize() {
var myOptions = {
zoom: 8,
center: new google.maps.LatLng(44.49, -91.30),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById(\'map_canvas\'),
myOptions);
var coord_data = new Array();
coord_data = '.$json.';
var marker;
for (var i = 1; i < coord_data.length; i++) {
console.log(coord_data[i]);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(coord_data[i]),
map:map
});
marker.setMap(map);
}
}
function loadScript() {
var script = document.createElement(\'script\');
script.type = \'text/javascript\';
script.src = \'//maps.googleapis.com/maps/api/js?sensor=false&callback=initialize\';
document.body.appendChild(script);
}
window.onload = loadScript;
</script>
</head>
<body>
<div id="map_canvas" style="width: 100%; height: 100%"></div>
</body>
</html>
';
#}
Any assistance would be greatly appreciated.
The problem is that when you assign the position here --
marker = new google.maps.Marker({
position:coord_data[i],
map:map
});
-- you give it a raw JSON object, but it's expecting a google.maps.LatLng object. You will want to assign it like this--
position: new google.maps.LatLng(coord_data[i].lon,coord_data[i].lat)
See here also for some good samples of the Gmaps API usage:
https://developers.google.com/maps/documentation/javascript/v2/examples/