How to insert Mysql Data text on Object [object HTMLCollection] - javascript

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.)

Related

Pass PHP variable to javascript to show location of IP on Google Maps [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Here on the same page U am using the php code to return an ip of domain and I would like to pass this php $ip variable to the below javascript code, in the button tag. How can I pass this php $ip variable into the below javascript code.
Here is the php submit part, without google maps:
<form method="post" action="">
<input type="text" name="name">
<input type="submit" name="submit" value="submit">
</form>
<?php
if(isset($_POST['submit']))
{
$ip = gethostbyname($_POST['name']);
echo $ip;
}
?>
Here is the javascript code in this code: I would like to pass above php $ip variable
I would like to remove the input tag and button tag in this javascript code because their existing two input and submit button tags on the single page
My goal in this project is to lookup the location of the IP and show it on google maps.
<script type="text/javascript">
$(function(){
try{
IPMapper.initializeMap("map");
//IPMapper.addIPMarker("111.111.111.111");
} catch(e){
//handle error
}
});
</script>
<input id="ip" name="ip" type="text" />
<button onclick="IPMapper.addIPMarker($('#ip').val());">Geocode</button>
<div id="map" style="height: 500px;width:500px; ">
</div>
For reference: the IPMapper code in javascript
/*!
* IP Address geocoding API for Google Maps
* http://lab.abhinayrathore.com/ipmapper/
* Last Updated: June 13, 2012
*/
var IPMapper = {
map: null,
mapTypeId: google.maps.MapTypeId.ROADMAP,
latlngbound: null,
infowindow: null,
baseUrl: "http://freegeoip.net/json/",
initializeMap: function(mapId){
IPMapper.latlngbound = new google.maps.LatLngBounds();
var latlng = new google.maps.LatLng(0, 0);
//set Map options
var mapOptions = {
zoom: 1,
center: latlng,
mapTypeId: IPMapper.mapTypeId
}
//init Map
IPMapper.map = new google.maps.Map(document.getElementById(mapId), mapOptions);
//init info window
IPMapper.infowindow = new google.maps.InfoWindow();
//info window close event
google.maps.event.addListener(IPMapper.infowindow, 'closeclick',
function() {
IPMapper.map.fitBounds(IPMapper.latlngbound);
IPMapper.map.panToBounds(IPMapper.latlngbound);
});
},
addIPArray: function(ipArray){
ipArray = IPMapper.uniqueArray(ipArray); //get unique array elements
//add Map Marker for each IP
for (var i = 0; i < ipArray.length; i++){
IPMapper.addIPMarker(ipArray[i]);
}
},
addIPMarker: function(ip){
ipRegex = /^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/;
if($.trim(ip) != '' && ipRegex.test(ip)){ //validate IP Address format
var url = encodeURI(IPMapper.baseUrl + ip + "?callback=?"); //geocoding url
$.getJSON(url, function(data) { //get Geocoded JSONP data
if($.trim(data.latitude) != '' && data.latitude != '0' && !isNaN(data.latitude)){ //Geocoding successfull
var latitude = data.latitude;
var longitude = data.longitude;
var contentString = "";
$.each(data, function(key, val) {
contentString += '<b>' + key.toUpperCase().replace("_", " ") + ':</b> ' + val + '<br />';
});
var latlng = new google.maps.LatLng(latitude, longitude);
var marker = new google.maps.Marker({ //create Map Marker
map: IPMapper.map,
draggable: false,
position: latlng
});
IPMapper.placeIPMarker(marker, latlng, contentString); //place Marker on Map
} else {
IPMapper.logError('IP Address geocoding failed!');
$.error('IP Address geocoding failed!');
}
});
} else {
IPMapper.logError('Invalid IP Address!');
$.error('Invalid IP Address!');
}
},
placeIPMarker: function(marker, latlng, contentString){ //place Marker on Map
marker.setPosition(latlng);
google.maps.event.addListener(marker, 'click', function() {
IPMapper.getIPInfoWindowEvent(marker, contentString);
});
IPMapper.latlngbound.extend(latlng);
IPMapper.map.setCenter(IPMapper.latlngbound.getCenter());
IPMapper.map.fitBounds(IPMapper.latlngbound);
},
getIPInfoWindowEvent: function(marker, contentString){ //open Marker Info Window
IPMapper.infowindow.close()
IPMapper.infowindow.setContent(contentString);
IPMapper.infowindow.open(IPMapper.map, marker);
},
uniqueArray: function(inputArray){ //return unique elements from Array
var a = [];
for(var i=0; i<inputArray.length; i++) {
for(var j=i+1; j<inputArray.length; j++) {
if (inputArray[i] === inputArray[j]) j = ++i;
}
a.push(inputArray[i]);
}
return a;
},
logError: function(error){
if (typeof console == 'object') { console.error(error); }
}
}
Maybe...
<button onclick="IPMapper.addIPMarker($('<?php echo $ip ?>').val());">Geocode</button>
Not an expert on javascript
A better solution would be to add the data to the element and use an event listener.
<button data-ip-marker="<?= htmlspecialchars($ip) ?>">Geocode</button>
and in JavaScript
$(document).on('click', '[data-ip-marker]', function() {
var marker = $('#' + this.getAttribute('data-ip-marker'));
if (marker.length) {
IPMapper.addIPMarker(marker.val());
}
});

Refresh PHP that grabs Co-Ords for google maps API

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>

Take a google map using ajax by php file

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!

Refresh google map markers from mysql

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.

Adding dynamic markers on to mapbox map file.

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 :)

Categories

Resources