Usamos cookies para medir audiência e melhorar sua experiência. Você pode aceitar ou recusar a qualquer momento. Veja sobre o iMasters.
Pessoal, boa tarde.
tenho uma situação aqui onde estou quebrando a cabeça para resolver.
tenho um arquivo js que precisa pegar dados que vem do banco(mysql).
não entendo praticamente nada de javascript, então, pensei em pegar um arquivo php fazer a consulta no banco, armazenar os resultados em variaveis. Feito isso ir no meu arquivo.js e imprimir o resultado do arquivo.php lá no js....é possível?
essa é a pagina que faço a consulta:
<?php
include '../conexao.php';
$sql = "select * from tb_localizacao;";
$resultado = mysql_query($sql);
$dados = mysql_fetch_array($resultado);
$latitude = $dados['latitude'];
$altitude = $dados['altitude'];
$endereco = $dados['endereco'];
?>
aqui é meu arquio javascript:
os dados precisam ser colocados na linha 2
**var myLatLng = new google.maps.LatLng(dadosDoBancoAqui1,dadosDoBancoAqui2**);
function initialize() {
var myLatLng = new google.maps.LatLng(-8.067270,-34.881859);
var roadAtlasStyles = [ { "featureType": "landscape", "elementType": "geometry.fill", "stylers": [ { "color": "#3c3e47" } ] },{ "elementType": "labels.text.fill", "stylers": [ { "color": "#FFFFFF" } ] },{ "elementType": "labels.text.stroke", "stylers": [ { "visibility": "off" } ] },{ "featureType": "road", "elementType": "geometry.fill", "stylers": [ { "color": "#50525f" } ] },{ "featureType": "road", "elementType": "geometry.stroke", "stylers": [ { "visibility": "on" }, { "color": "#808080" } ] },{ "featureType": "poi", "elementType": "labels", "stylers": [ { "visibility": "off" } ] },{ "featureType": "transit", "elementType": "labels.icon", "stylers": [ { "visibility": "off" } ] },{ "featureType": "poi", "elementType": "geometry", "stylers": [ { "color": "#808080" } ] },{ "featureType": "water", "elementType": "geometry.fill", "stylers": [ { "color": "#3071a7" }, { "saturation": -65 } ] },{ "featureType": "road", "elementType": "labels.icon", "stylers": [ { "visibility": "off" } ] },{ "featureType": "landscape", "elementType": "geometry.stroke", "stylers": [ { "color": "#bbbbbb" } ] } ];
var mapOptions = {
zoom: 14,
center: myLatLng,
disableDefaultUI: true,
scrollwheel: false,
navigationControl: false,
mapTypeControl: false,
scaleControl: false,
draggable: false,
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'roadatlas']
}
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: 'img/location-icon.png',
title: '',
});
var contentString = '<div style="max-width: 300px" id="content">'+
'<div id="bodyContent">'+
'<h5 class="color-primary"><strong>Concórdia Eletrícidade</strong></h5>' +
'<p style="font-size: 12px"><strong>Rua da Concórdia, 393 - São José, Recife - PE, 50020-050, Brasil<br/>Fone: 81 3224-2817</strong>' +
'</div>'+
'</div>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
var styledMapOptions = {
name: 'US Road Atlas'
};
var usRoadMapType = new google.maps.StyledMapType(
roadAtlasStyles, styledMapOptions);
map.mapTypes.set('roadatlas', usRoadMapType);
map.setMapTypeId('roadatlas');
}
google.maps.event.addDomListener(window, "load", initialize);
Acho que fui claro, alguém poderia, por favor, me ajudar? Obrigado!
>
Sim, é possível mas não é uma boa idéia.
Nesses casos é melhor utilizar ajax. Que é uma tecnologia com javascript, para "ir no servidor e voltar com a resposta", fazendo um request http, e trazendo direto pro js.
William, tem algum texto para indicar? Como falei, não entendo nada de js...ajax...hehe
<!DOCTYPE html>
<html>
<head>
<title>Cinturão Digital</title>
<script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
<meta charset="utf-8">
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script src="js/markerwithlabel.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
var mapCenter = new google.maps.LatLng(-5.462284, -38.457665); // Coordenadas iniciais do mapa
var map;
var tecnico_20m = 'Esta no local em 20 Minutos: ';
var tecnico_2h = 'Levar o Gerador em 2 Horas: ';
var infra = 'Infraestrutura: ';
var rompimento = 'Rompimento de Fibra: '; //Variaveis responsaveis por exibir os registros feitos no sistema
map_initialize(); // inicia o Mapa
function map_initialize()
{
var googleMapOptions = // opções da API do google maps3
{
center: mapCenter, // Posição do Mapa
zoom: 8, // Zoom inicial do Mapa
zoomControlOptions: { // opções da API do google maps3
style: google.maps.ZoomControlStyle.SMALL
},
scaleControl: true, // habilitando controle de escala
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var legendDiv = document.createElement('DIV'); //Responsavel pela Legeda
var legend = new Legend(legendDiv, map); //Responsavel pela Legeda
legendDiv.index = 1; //Responsavel pela Legedas
map = new google.maps.Map(document.getElementById("google_map"), googleMapOptions);
mapTypeId: google.maps.MapTypeId.ROADMAP
map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(legendDiv); //Reposável pela Legenda
// Essas variaveis sao resposaveis pelo desenho do citurão digital criado por Mateus Aires
var flightPlanCoordinates = [
new google.maps.LatLng( -7.762445,-39.063464), // Coordenadas inicio do cinturao
new google.maps.LatLng( -7.313622,-38.939572), // Coordenadas milagres
];
var flightPath = new google.maps.Polyline({ //Função responsavel por mostra as linhas do cinturão
path: flightPlanCoordinates,
geodesic: true,
strokeColor: '#FF0000', // cor da linha
strokeOpacity: 4.0, // Opacidade
strokeWeight: 2 // Tamanho da Linha
});
flightPath.setMap(map) //Responsável que mostra a linha
//Carrega o arquivo php ou XML
$.get("map_process.php", function (data) {
$(data).find("marker").each(function () {
var name = $(this).attr('name');
var type = $(this).attr('type');
var tecnico_secundario= '<p>'+ '<b>' + tecnico_2h + '</b>' +$(this).attr('tecnico_secundario')+'</p>'; //var tecnico em 2 horas
var tecnico_primario = '<p>'+ '<b>'+tecnico_20m + '</b>' + $(this).attr('tecnico_primario') +'</p>'; //var tecnico em 20 minutos
var empresa = '<p>' + '<b>' + infra + '</b>' + $(this).attr('empresa'); + '</p>'; //var infraestrura na empresa
var address = '<p>'+ '<b>' + rompimento + '</b>' + $(this).attr('address') +'</p>'; // var do rompimento de fibra no adress
var point = new google.maps.LatLng(parseFloat($(this).attr('lat')),parseFloat($(this).attr('lng')));
create_marker(point, name, address, tecnico_primario,tecnico_secundario, empresa, false, false, false, "img/icon-cpd-brisanet.png");
if (name == "CPD - Crateus/CE WireLink") {
create_marker(point, name, address, tecnico_primario,tecnico_secundario, empresa, false, false, false, "img/icon-cpd-wirelink.png");
};
if (name == "CPD- Sao Luis do Curu/CE WireLink") {
create_marker(point, name, address, tecnico_primario,tecnico_secundario, empresa, false, false, false, "img/icon-cpd-wirelink.png");
};
if (name == "CPD - Pacajus/CE WireLink") {
create_marker(point, name, address, tecnico_primario,tecnico_secundario, empresa, false, false, false, "img/icon-cpd-wirelink.png");
};
if (name == "CPD - Itapage/CE WireLink") {
create_marker(point, name, address, tecnico_primario,tecnico_secundario, empresa, false, false, false, "img/icon-cpd-wirelink.png");
};
if (name == "CPD- Sao Luis do Curu/CE WireLink") {
create_marker(point, name, address, tecnico_primario,tecnico_secundario, empresa, false, false, false, "img/icon-cpd-wirelink.png");
};
if (name == "CPD - Carire/CE WireLink") {
create_marker(point, name, address, tecnico_primario,tecnico_secundario, empresa, false, false, false, "img/icon-cpd-wirelink.png");
};
});
});
//Criar um novo ponto no mapa
google.maps.event.addListener(map, 'rightclick', function(event) {
var EditForm = '<p><div class="marker-edit">'+
'<form action="ajax-save.php" method="POST" name="SaveMarker" id="SaveMarker">'+
'<label for="pName"><span>Nome do CPD :</span><input type="text" name="pName" class="save-name" placeholder="Enter Title" maxlength="40" /></label>'+
'<label for="pType"><span>Tipo :</span> <select name="pType" class="save-type"><option value="Auto">Auto</option></select></label>'+
'<label for="pTecnico_primario"><span>Tecnico :</span> <select name="pTecnico_primario" class="save-tecnico_primario"><option value="Auto"></option></select></label>'+
'<label for="pTecnico_secundario"><span>2º Técnico :</span> <select name="pTecnico_secundario" class="save-tecnico_secundario"><option value="Auto">Auto</option></select></label>'+
'<label for="pEmpresa"><span>Empresa:</span> <select name="pEmpresa" class="save-empresa"><option value="Auto">Auto</option></select></label>'+
'<label for="pDesc"><span>Contatos :</span><textarea name="pDesc" class="save-desc" placeholder=Observações maxlength="150"></textarea></label>'+
'</form>'+
'</div></p><button name="save-marker" class="save-marker">Salvar Ponto</button>';
//Criar um novo Marker no mapa.
create_marker(event.latLng, 'Novo Ponto', EditForm, true, true, true, "img/icon-cpd-brisanet.png");
});
}
function create_marker(MapPos, MapTitle, MapDesc, MapTecnico_primario, MapTecnico_secundario, MapEmpresa, InfoOpenDefault, DragAble, Removable, iconPath)
{
//Mostra os markes
var marker = new MarkerWithLabel({
position: MapPos,
map: map,
draggable:DragAble,
raiseOnDrag: true,
animation: google.maps.Animation.DROP,
title: MapTitle,
labelContent: MapTitle,
labelClass: "labels", // the CSS class for the label
labelStyle: {opacity: 0.75},
icon: iconPath
});
//Contem as estrutura que são mostradas no marker do mapa
var contentString = $('<div class="marker-info-win">'+
'<div class="marker-inner-win"><span class="info-content">'+
'<b><h1 class="marker-heading">'+MapTitle+'</h1></b>'+
MapDesc+MapTecnico_primario+MapTecnico_secundario+ MapEmpresa+
'</span><button name="remove-marker" class="remove-marker" title="Remove Marker"></button>'+ // caso precise habilitar para remover !
'</div></div>');
//Create an infoWindow
var infowindow = new google.maps.InfoWindow();
//set the content of infoWindow
infowindow.setContent(contentString[0]);
var removeBtn = contentString.find('button.remove-marker')[0];
var saveBtn = contentString.find('button.save-marker')[0];
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
var mTecnico_primario = contentString.find('select.save-tecnico')[0].value; //salvando o tecnico
var mTecnico_secundario = contentString.find('select.save-tecnico_secundario')[0].value; //type of marker
var mEmpresa = contentString.find('select.save-empresa')[0].value; //type of marker
if(mName =='' || mDesc =='')
{
alert("Por favor digita a descrição");
}else{
save_marker(marker, mName, mDesc, mType, mTecnico_primario, mTecnico_secundario, mEmpresa, mReplace); //call save marker function
}
});
}
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);
}
}
function remove_marker(Marker)
{
/* determine whether marker is draggable
new markers are draggable and saved markers are fixed */
if(Marker.getDraggable())
{
Marker.setMap(null); //just remove new marker
}
else
{
//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
}
});
}
}
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,tecnico : mTecnico_primario, tecnico_secundario: mTecnico_secundario,empresa: mEmpresa }; //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(false); //set marker to fixed
Marker.setIcon('icon-cpd-brisanet.png'); //replace icon
},
error:function (xhr, ajaxOptions, thrownError){
alert(thrownError); //throw any errors
}
});
}
});
function Legend(controlDiv, map) {
// Set CSS styles for the DIV containing the control
// Setting padding to 5 px will offset the control
// from the edge of the map
controlDiv.style.padding = '5px';
// Set CSS for the control border
var controlUI = document.createElement('DIV');
controlUI.style.backgroundColor = 'white';
controlUI.style.borderStyle = 'solid';
controlUI.style.borderWidth = '1px';
controlUI.title = 'Legend';
controlDiv.appendChild(controlUI);
// Set CSS for the control text
var controlText = document.createElement('DIV');
controlText.style.fontFamily = 'Arial,sans-serif';
controlText.style.fontSize = '12px';
controlText.style.paddingLeft = '4px';
controlText.style.paddingRight = '4px';
// Add the text
controlText.innerHTML = '<b>Legenda*</b><br />' +
'<img src="img/icon-cpd-brisanet.png" /> CPD Brisanet Telecomunicações<br/>' +
'<img src="img/icon-cpd-wirelink.png"/> CPD WireLink<br/>' +
'<img src="img/icon-cpd-mobil.png"/> CPD Mobil Telecom<br />' +
'<img src="img/cinturao.png"/> Cinturão Digital<br />'
controlUI.appendChild(controlText);
}
</script>
<style type="text/css">/ width and height of google map /
#google_map {width: 100%; height: 950px;margin-top:0px;margin-left:auto;margin-right:auto;}
/ Marker Edit form /
.marker-edit label{display:block;margin-bottom: 5px;}
.marker-edit label span {width: 200px;float: left;}
.marker-edit label input, .marker-edit label select{height: 40px;}
.marker-edit label textarea{height: 80px;}
.marker-edit label input, .marker-edit label select, .marker-edit label textarea {width: 80%;margin:0px;padding-left: 5px;border: 1px solid #DDD;border-radius: 3px;}
/ Marker Info Window /
h1.marker-heading{color: #585858;margin: 0px;padding: 0px;font: 25px "Trebuchet MS", Arial;border-bottom: 1px dotted #D8D8D8;}
div.marker-info-win {max-width: 500px;margin-right: 40px;}
div.marker-info-win p{padding: 0px;margin: 10px 0px 20px 0;}
div.marker-inner-win{padding: 5px;}
button.save-marker, button.remove-marker{border: none;background: rgba(0, 0, 0, 0);color: #00F;padding: 0px;text-decoration: underline;margin-right: 10px;cursor: pointer;
}
.labels {
color: white;
background-color: black;
font-family: "ubuntu";
font-size: 10px;
width:170px;
border: 2px solid black;
white-space: nowrap;
}
</style>
</head>
<body>
<div id="google_map"></div>
</body>
</html>
ARQUIVO PHP
<?php
//PHP 5 +
// database settings
$db_username = 'root';
$db_password = '';
$db_name = '';
$db_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);
$mTecnico_primario = filter_var($_POST["tecnico_primario"], FILTER_SANITIZE_STRING);
$mTecnico_secundario = filter_var($_POST["tecnico_secundario"], FILTER_SANITIZE_STRING);
$mEmpresa = filter_var($_POST["empresa"], FILTER_SANITIZE_STRING);
$results = $mysqli->query("INSERT INTO markers (name, address, lat, lng, type , tecnico_primario, tecnico_secundario,empresa) VALUES ('$mName','$mAddress',$mLat, $mLng, '$mType','$mTecnico_primario','$mTecnico_secundario','$mEmpresa')");
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);
$newnode->setAttribute("tecnico_primario", $obj->tecnico_primario);
$newnode->setAttribute("tecnico_secundario", $obj->tecnico_secundario);
$newnode->setAttribute("empresa", $obj->empresa);
}
echo $dom->saveXML();
Sim, é possível mas não é uma boa idéia.
Nesses casos é melhor utilizar ajax. Que é uma tecnologia com javascript, para "ir no servidor e voltar com a resposta", fazendo um request http, e trazendo direto pro js.