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 :)
Related
I am making the website with food ordering and delivering module. For that I am using Mapbox and here first i want to select the store-address location with longitude and latitude which i want to select from my addresses table.I dont know how to display the address-location with the longitude and latitude of specific store-address and show with the marker.
Here is the code of the Controller function for getting the value of longitude and latitude of specific address with id :
public function mapofstore($id)
{
$data = DB::Table('addresses')->select('longitude','latitude')->where('id',$id)->get();
// dd($data);
return view('MainAdmin.frontend.reports.storelocation',compact('data'));
}
Here is the code of javascript reference from the official doc of Mapbox:
<div class="container">
<div class="map-area">
<div id='map' style=" width:100%; height: 500px; border: solid;border-color: #1e828de8;border-radius: 1%;"></div>
<pre id="info"></pre>
</div>
</div>
<script>
mapboxgl.accessToken = 'My_MapBox_Api';
var map = new mapboxgl.Map({
container: 'map',
style: 'Style_URL'
});
navigator.geolocation.getCurrentPosition(successLocation,errorLocation,{
enableHighAccuracy: true
})
function successLocation(){
console.log(position)
}
function errorLocation(){
}
function getReverseGeocodingData(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
// This is making the Geocode request
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'latLng': latlng }, (results, status) =>{
if (status !== google.maps.GeocoderStatus.OK) {
alert(status);
}
// This is checking to see if the Geoeode Status is OK before proceeding
if (status == google.maps.GeocoderStatus.OK) {
console.log(results);
var address = (results[0].formatted_address);
}
});
}
function onClick(event){
document.getElementById('lat').value = event.latlng.lat;
document.getElementById('lng').value = event.latlng.lng;
var group = L.featureGroup();
group.id = 'group';
var p_base = L.circleMarker([event.latlng.lat ,event.latlng.lng], {
color: '#fff',
fillColor: '#6a97cb',
fillOpacity: 1,
weight: 1,
radius: 6
}).addTo(group);
map.addLayer(group);
}
// function START for getting lng,lat of current mouse position----------------
map.on('mousemove', (e) => {
document.getElementById('info').innerHTML =
// `e.point` is the x, y coordinates of the `mousemove` event
// relative to the top-left corner of the map.
JSON.stringify(e.point) +
'<br />' +
// `e.lngLat` is the longitude, latitude geographical position of the event.
JSON.stringify(e.lngLat.wrap());
});
// function END for getting lng,lat of current mouse position------------------
// function START for getting current location----------------
map.addControl(new mapboxgl.NavigationControl());
map.addControl(
new mapboxgl.GeolocateControl({
positionOption:{
enableHighAccuracy:true
},
trackUserLocation:true
}));
// function END for getting current location------------------
// function for Direction and Pointing of one Point-----------
map.addControl(
new MapboxDirections({
accessToken: mapboxgl.accessToken
}),
'top-left'
);
const addMarker = () => {
const marker = new mapboxgl.Marker()
// const minPopup = new mapboxgl.Popup({closeButton: false, closeOnClick: false})
minPopup.setHTML("")
marker.setPopup(minPopup)
marker.setLngLat([36.67981,22.10816])
marker.addTo(map)
marker.togglePopup();
}
map.on("load",addMarker)
$.getJSON("https://jsonip.com?callback=?", function (data) {
var ip = data;
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
// console.log(url);
$.ajax({
url : '{{URL::to('updateip')}}' + '/' + id,
type: 'POST',
data: {_token: CSRF_TOKEN,
"ip": ip,
"id": id
},
dataType: 'json',
success: function(response){
}
});
});
// function for Direction and Pointing of one Point-----------
function show_marker(Lng,Lat,date,In,Out,hname,hin,hout)
{
const marker = new mapboxgl.Marker({ "color": "#b40219" })
// const minPopup = new mapboxgl.Popup({closeButton: false, closeOnClick: false})
minPopup.setHTML("<strong><b>IN n OUT DATE:</b><br>"+date+"<br><b>IN n OUT TIME:</b><br>"+In+"-"+Out+"<br><b>HOTEL NAME:</b><br>"+hname+"<br><b>HOTEL IN n OUT:</b><br>"+hin+"-"+hout+"</strong>")
// marker.setPopup(minPopup)
marker.setLngLat([Lng,Lat])
// marker.setRotation(45);
marker.addTo(map)
}
const popup = new mapboxgl.Popup({ closeOnClick: false })
.setLngLat([-96, 37.8])
.setHTML('<h1>Hello World!</h1>')
.addTo(map);
</script>
You already have made addMarker function. You just have to pass the lat long there from your data collection. I am assuming that you are using the blade template only. In blade template, you can get your data to javascript variable easily.
var data = <?php echo json_encode($data); ?>
Then you have to parse encoded data into new variables using
var newData = JSON.parse(data);
After that, you can use your newData to get the lat long which you can pass in your function and use it.
var lat = newData[0].latitude
var lng = newData[0].longitude
const addMarker = (lat, lng) => {
const marker = new mapboxgl.Marker()
minPopup.setHTML("")
marker.setPopup(minPopup)
marker.setLngLat([lng,lat])
marker.addTo(map)
marker.togglePopup();
}
// calling add marker
addMarker(lat, lng);
Reference for passing data to javascript. Please note that these methods are different in different Laravel versions.
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 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 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.