I have been working on a little app for a friend right now I am encoding a mysql query with
<?php
include 'dbconnect.php';
$result = mysql_query("SELECT * FROM coords ORDER BY name DESC") or die ("Could not
query");
while($row = mysql_fetch_array($result)) {
$r[] = array(
"name" => $row['name'],
"lat" => $row['lat'],
"lng" => $row['lng'],
"speed" => $row['speed'],
"altitude" => $row['altitude'],
"distance" => $row['distance']
);
}
$encoded = json_encode($r);
echo$encoded;
mysql_close($conn);
?>
The problem is there is no array position key associated with each entry to tell the json that this whole thing is a key
Array(
[1] = ( "name" => $row['name'],
"lat" => $row['lat'],
"lng" => $row['lng'],
"speed" => $row['speed'],
"altitude" => $row['altitude'],
"distance" => $row['distance']),
[2] = ( "name" => $row['name'],
"lat" => $row['lat'],
"lng" => $row['lng'],
"speed" => $row['speed'],
"altitude" => $row['altitude'],
"distance" => $row['distance'])));
for every row in the database basically I want to parse each row of the database into an array with his own key so i can call it as a javascript object and draw it ona google map.
ive tried
<?php
include 'dbconnect.php';
$count = 0;
$result = mysql_query("SELECT * FROM coords ORDER BY name DESC") or die ("Could not
query");
while($row = mysql_fetch_array($result)) {
$count = $count + 1;
$r[$count] = array(
"name" => $row['name'],
"lat" => $row['lat'],
"lng" => $row['lng'],
"speed" => $row['speed'],
"altitude" => $row['altitude'],
"distance" => $row['distance']
);
}
$encoded = json_encode($r);
echo$encoded;
mysql_close($conn);
?>
but that didn't work and theen there is my json code im not sure its right. Below is my map code can you look at the section of the json code and tellme if that is how im supposed to call the array I want to write in my php file. Also if I'm drawing the marker right fro the array. Thanks
var watchID;
var latitudeAndLongitudeCurrent;
var route = false;
var firstMapCall;
var directionsDisplay; // Declare a variable
of renderer object
var directionsService = new google.maps.DirectionsService(); // Instantiate a
directions service.
var map;
var currentMarker;
var carMarker;
var usermarker;
var markloc;
var myOptions =
{
zoom:14,
mapTypeId: google.maps.MapTypeId.ROADMAP,
enableHighAccuracy: true,
zoomControlOptions: {
position: google.maps.ControlPosition.TOP_RIGHT
},
maximumAge: 10000
};
function initializeMyMap()
{
directionsDisplay = new google.maps.DirectionsRenderer(); // Instantiate a
renderer object.
//directionsDisplay.suppressMarkers = true; //removes direction markers
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
directionsDisplay.setMap(map); // bind the map to
the renderer
}
function showLocation(){
firstMapCall = true;
//if initalize hasn't been called, call it
if(directionsDisplay == null) {
initializeMyMap();
}
watchID = navigator.geolocation.watchPosition(onSuccessShowLoc, onError, myOptions);
}
function setMapBounds(position){
var mapBounds = new google.maps.LatLngBounds();
mapBounds.extend(position);
map.fitBounds(mapBounds);
zoomChangeBoundsListener =
google.maps.event.addListenerOnce(map, 'bounds_changed', function(event) {
if (this.getZoom()){
this.setZoom(18);
}
});
resize();
}
// onSuccess Geolocation
function onSuccessShowLoc(position) {
latitudeAndLongitudeCurrent = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
if(firstMapCall == true){
var result = retrieveLocation();
setMapBounds(latitudeAndLongitudeCurrent);
if(result != null){
addCarMarker(result);
}
firstMapCall = false;
}
deleteOverlays();
addCurrentLocMarker(latitudeAndLongitudeCurrent);
//ajax
var ajaxRequest;
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// This sets the users location in the database
var lat = position.coords.latitude;
var lng = position.coords.longitude;
var parseid = id;
var queryString = "?lat=" + lat ;
queryString += "&lng=" + lng + "&id=" + parseid;
console.log('string combination');
ajaxRequest.open("GET", "data.php" + queryString, true);
ajaxRequest.send(null);
console.log('executed');
}
// Removes the overlays from the map, but keeps them in the array
function deleteOverlays() {
if (currentMarker) {
currentMarker.setMap(null);
}
}
function deleteCarOverlay() {
if (carMarker) {
carMarker.setMap(null);
}
}
function deleteUserOverlay() {
if (usermarker) {
usermarker.setMap(null);
}
}
function addCurrentLocMarker(location) {
marker = new google.maps.Marker({
position: location,
icon: 'http://www.wolfdoginfo.net/app/snowboarding.png',
map: map
});
currentMarker = marker;
}
function addCarMarker(location) {
marker = new google.maps.Marker({
draggable: true,
raiseOnDrag: false,
icon:'http://www.wolfdoginfo.net/app/revolt.png',
map: map,
position: location
});
carMarker = marker;
}
var myVar=setInterval(function(){showData()},3000);
function showData(str)
{
calluserlocation();
}
function calluserlocation(){
console.log('calluserlocation fires');
$.ajax( {
url: "getdata.php",
type: "GET",
dataType: "json",
success: function(data) { for (var i = 0; i < data.length; i++) { markloc = new
google.maps.LatLng(data[i].b, data[i].c); adddata(markloc); } }, error:
function(data) { console.log( "error with the json" ); } });
console.log("sucessful run of function");
}
function adddata(markloc){
marker = new google.maps.Marker({
position: markloc,
icon: 'http://www.wolfdoginfo.net/app/cropcircles.png',
map: map
});
deleteUserOverlay();
usermarker = marker;
}
function calcRoute()
{
var theDestination = retrieveLocation();
if(theDestination == null){
alert("Error: No Friend meeting place has been saved.");
return null;
}
var request = // Instantiate a DirectionsRequest object
{
//origin is LatLng object
origin: latitudeAndLongitudeCurrent,
//destination is LatLng object
destination: theDestination,
travelMode: google.maps.DirectionsTravelMode.WALKING
};
directionsService.route(request, // call route() to request directions service
function(result, status)
{
if (status == google.maps.DirectionsStatus.OK)
{
directionsDisplay.setOptions({ preserveViewport: true });
directionsDisplay.setDirections(result); // draw the routes
// put text directions on directions_panel
directionsDisplay.setPanel(document.getElementById("directions_panel"));
route=true;
}
}
);
}
function textDirections()
{
if(route == false){
calcRoute();
}
}
function resize(){
var map_page = document.getElementById('show');
var map_container = document.getElementById('the_map_container');
var header = document.getElementById('thehead');
var newHeight = map_page.offsetHeight - 170;
map_container.style.height = newHeight + 'px';
// trigger a resize event on the map so it reflects the new size
if(map != null) {
google.maps.event.trigger(map, 'resize');
}
}
If you want your name as the key then do this
$r = array(); // A best practice to declare it's an array
while($row = mysql_fetch_assoc($result)) { // fetch_assoc gives you keys based on your field names
$r[$row['name']] = array( ... );
}
Also, a PSA, be sure to use mysqli as mysql has been depreciated.
Related
Hello guys I need help from you. I'm coding a web application using laravel framework. I've recorded logitudes, latitudes and other informations in the database. I want to fetch those informations and display their marker on google map. All examples I'm getting are for PHP scratch code. Is there anyone who can help me how to do it in laravel?
HERE IS THE DATABASE CODE
Schema::create('alertes', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('code');
$table->string('code_client');
$table->string('client_category');
$table->string('longitude');
$table->string('latitude');
$table->timestamps();
});
HERE IS MY BLADE FILE
<div id="map" style="width:100%;height:400px;"></div>
</div>
</div>
</div>
</div>
#endsection()
#section('custom-script')
<script type="text/javascript" src="{{asset('assets')}}/map/carte_alertes.js"></script>
<script
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCnyJJ2gorvX0rsuhBJLNUsfyioWSSep2Q&callback=init"></script>
<script>
</script>
#endsection
HERE IS MY SCRIPT.JS
<script>
function makeRequest(url, callback) {
var request;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
} else {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
request.onreadystatechange = function () {
if (request.readyState === 4 && request.status === 200) {
callback(request);
}
}
request.open("GET", url, true);
request.send();
}
var map;
// Beni
var center = new google.maps.LatLng(0.496422, 29.4751);
var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow();
function init() {
var mapOptions = {
zoom: 13,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map"), mapOptions);
makeRequest("{{route('alertes.index')}}", function (data) {
var data = JSON.parse(data.responseText);
for (var i = 0; i < data.length; i++) {
displayLocation(data[i]);
}
});
}
// displayLocation method
function displayLocation(location) {
var content = '<div class="infoWindow"><strong>' + location.code_client + '</strong>'
+ '<br/>' + location.client_category + '</div>';
if (parseInt(location.latitude) == 0) {
geocoder.geocode({'client_category': location.client_category}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: location.code_client
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(content);
infowindow.open(map, marker);
});
}
});
} else {
var position = new google.maps.LatLng(parseFloat(location.latitude), parseFloat(location.longitude));
var marker = new google.maps.Marker({
map: map,
position: position,
title: location.code_client
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(content);
infowindow.open(map, marker);
});
}
}
change callback=initMap not callback=init
src="https://maps.googleapis.com/maps/api/js?key=yourapikey&callback=init"></script>
try your data format this way
public function mapMarker(){
$locations = Alerte::all();
$map_markes = array ();
foreach ($locations as $key => $location) {
$map_markes[] = (object)array(
'code' => $location->code,
'code_client' => $location->code_client,
'client_category' => $location->client_category,
'longitude' => $location->longitude,
'latitude' => $location->latitude,
);
}
return response()->json($map_markes);
}
copy this code and re-place this code
content : `<div><h5>${Number(datas[index].latitude)}</h5><p><i class="icon address-icon"></i>${Number(datas[index].longitude)}</p></div>`
Still having the problem
HERE IS MY NE
function initMap(){
var mapElement = document.getElementById('map');
var url = '/map-marker';
async function markerscodes(){
var data = await axios(url);
var alerteData = data.data;
mapDisplay(alerteData);
}
markerscodes();
function mapDisplay(datas) {
//map otions
var options ={
center :{
lat:Number(datas[0].latitude), lng:Number(datas[0].longitude)
},
zoom : 10
}
//Create a map object and specify the DOM element for display
var map = new google.maps.Map(mapElement, options);
var markers = new Array();
for (let index = 0; index < datas.length; index++){
markers.push({
coords: {lat: Number(datas[index].latitude), lng:Number(datas[index].longitude)},
content : '<div><h5>${datas[index].code_du_suspect}</h5><p><i class="icon address-icon"></i>${datas[index].etat_du_suspect}</p></div>'
})
}
//looping through marker
for (var i = 0; i < markers.length; i++){
//une fontion a creer si dessous
addMarker(markers[i]);
}
function addMarker(props){
var marker = new gooogle.maps.Marker({
position : props.coords,
map: map
});
if(props.iconImage){
marker.setIcon(props.iconImage);
}
if(props.content){
var infoWindow = new google.maps.infoWindow({
content : props.content
});
marker.addListener('click', function () {
infoWindow.open(map, marker);
});
}
}
}
}
I try to show on a google map markers that are near the current positon. If the map is dragged it will update the center coordinates and recalculate the markers around that center. The initial markers around the current users positon are showing correctly but when i drag the map they stay all the time the same. The update and the POST both is happening (my guess that the POST is not finished before the markers reload, so the old ones stay). The sourrounding markers are stored in a session variable.
Controller showNearbyUsers method:
/**
* Shows the users near the current one
*
* #return void
*/
public static function showNearbyUsers($centerlat,$centerlng)
{
try {
// Delete the session variable
if (Session::has('nearbies'))
{
Session::forget('nearbies');
}
// Define max, min for lat and lng
$centerlatlow = $centerlat-0.25;
$centerlathigh = $centerlat+0.25;
$centerlnglow = $centerlng-0.25;
$centerlnghigh = $centerlng+0.25;
$nearbies = DB::table('positions')->join('users', 'users.id', '=', 'positions.users_id')
->where('users_id', '!=', Auth::id())
->whereBetween('lat', array($centerlatlow, $centerlathigh))
->whereBetween('lng', array($centerlnglow, $centerlnghigh))
->select('positions.*', 'users.name', 'users.level')
->get();
if ($nearbies) {
return Session::put('nearbies', $nearbies);
}
} catch(\Exception $e) {
Session::flash('message', 'An error occured with your localization. Enable GPS and refresh.');
Session::flash('alert-class', 'alert-danger');
}
}
View Script
<script>
// Auto adjust map div
$(window).resize(function () {
var h = $(window).height(),
offsetTop = 220; // Calculate the top offset
$('#map_canvas').css('height', (h - offsetTop));
}).resize();
// Setup token security
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
// Attributes
var map;
var geocoder;
var markers = Array(); // Contains x,y
var users = Array(); // Contains whole user info
var current = Array();
var infoWindows = Array();
var mapCenter;
// Test initialize users array
//users = [['Brugg',47.47963,8.18465],['Aarau',47.39340,8.04312],['Baden',47.47377,8.30647]];
// Initialize the map with logged in user
function initialize() {
geocoder = new google.maps.Geocoder();
getLocation();
}
// Set nearby user markers
function setMarkers(list) {
for(var i=0; i<list[0].length; i++){
var element = (list[0])[i];
var nearbyLatLng = new google.maps.LatLng(element['lat'], element['lng']);
console.log((list[0])[i]);
markers[i] = new google.maps.Marker({
position: nearbyLatLng,
map: map,
title: element['name'],
infoWindowIndex : i
});
infoWindows[i] = new google.maps.InfoWindow({
content : element['name']
});
google.maps.event.addListener(markers[i], 'click',
function(event)
{
infoWindows[this.infoWindowIndex].open(map, this);
}
);
}
}
// Delete nearby user markers
function deleteMarkers() {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
}
// Map dragging listener. Updates the nearby users markers
function mapDragListener() {
google.maps.event.addListener(map, 'dragend', function() {
deleteMarkers();
mapCenter = map.getCenter();
$.ajax({
type: "POST",
url: "updatenearbies/"+mapCenter.lat()+"/"+mapCenter.lng(),
async: false
});
#if(Session::has('nearbies'))
<?php $test = Session::get('nearbies'); ?>
users = [<?php echo json_encode($test); ?>];
console.log(users);
#endif
setMarkers(users);
});
}
// Map zoom listener. Updates the nearby users markers
function mapZoomListener() {
}
// Get current user location
function getLocation() {
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(geoSuccess, geoError);
} else {
alert("Geolocation is not supported by this browser.");
}
}
// If success in finding current position
function geoSuccess(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
// Send to geocoordinates.php and save to DB
$.post("updateme/"+lat+"/"+lng);
mainMapCalc(lat, lng);
}
// If no success in finding current position
function geoError() {
alert("Please enable Geo-Location and Refresh the Website.");
}
// Set the logged in users and build up the environment
function mainMapCalc(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
if(results[1]) {
//formatted address
var address = results[0].formatted_address;
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var myOptions = {
zoom: 18,
center: results[0].geometry.location,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
mapCenter = map.getCenter();
$.ajax({
type: "POST",
url: "updatenearbies/"+mapCenter.lat()+"/"+mapCenter.lng(),
async: false
});
<?php $test = Session::get('nearbies'); ?>
users = [<?php echo json_encode($test); ?>];
setMarkers(users); // Set initial nearby markers
mapDragListener(); // Register Listener
//mapZoomListener(); // TODO: Register Listener
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
} else {
alert("Geocoder Error// No results found");
}
} else {
alert("Geocoder Error// Failed due to: " + status);
}
});
}
// Show Map
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Where is here the problem?
Thanks in advance
It looks like the problem is that you are sending out the ajax request, but you are not doing anything with the returned data. Try changing
$.ajax({
type: "POST",
url: "updatenearbies/"+mapCenter.lat()+"/"+mapCenter.lng(),
async: false
});
to
$.ajax({
type: "POST",
url: "updatenearbies/"+mapCenter.lat()+"/"+mapCenter.lng(),
success: function(data, textStatus, jqXHR) {
// request succeeded
// data - response from server
},
error: function (jqXHR, textStatus, errorThrown){
// the request failed
}
});
Also note that async: false is deprecated: https://api.jquery.com/jQuery.ajax/#options, so you should use callbacks as shown above.
I am working on a new project and I am new to the Google maps API.
I need your help to mark only one marker on the map. Our clients would indicate their location with a right click and only if they remove the existing marker they reinsert their location.
I have tried if and else and the only result is that the map does not load.
I have created a fiddle with the code hope it helps: http://jsfiddle.net/JG9bG/
$(document).ready(function () {
var mapCenter = new google.maps.LatLng(39.39987199999999, -8.224454000000037); //Google map Coordinates
var map;
map_initialize(); // initialize google map
//############### Google Map Initialize ##############
function map_initialize() {
var googleMapOptions = {
center: mapCenter, // map center
zoom: 7, //zoom level, 0 = earth view to higher value
maxZoom: 18,
minZoom: 7,
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, "http://google.com/mapfiles/ms/micons/blue.png");
});
});
//Right Click to Drop a New Marker
myListener = 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="pid"><span> Property Id: </span><input type="text" readonly name="pid" class="save-propid" value="<?php echo $prop_id;?>" maxlength="40" /></label>' +
'<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="Rent">Rent</option><option value="Sell">Sell</option><option value="Holiday Rentals">Holiday Rentals</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, 'Insert your Property Location', EditForm, true, true, true, "http://google.com/mapfiles/ms/micons/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: DragAble,
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
var mpid = contentString.find('input.save-propid')[0].value; //prop id
if (mName == '' || mDesc == '') {
alert("Please enter Name and Description!");
} else {
save_marker(marker, mName, mDesc, /*mType, */ mpid, 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 */
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: "http://.../.../.../cpanel.php?exe=client_properties/google/map_process",
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, */ mpid, 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, */
propid: mpid
}; //post variables
console.log(replaceWin);
$.ajax({
type: "POST",
url: "http://.../.../.../cpanel.php?exe=client_properties/google/map_process",
data: myData,
success: function (data) {
replaceWin.html(data); //replace info window with new html
Marker.setDraggable(false); //set marker to fixed
Marker.setIcon('http://google.com/mapfiles/ms/micons/blue.png'); //replace icon
},
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError); //throw any errors
}
});
}
});
Thanks for your help
Backend:
<?php
//PHP 5 +
// database settings
$db_username = '';
$db_password = '';
$db_name = '';
$db_host = 'localhost';
//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 tblmarkers WHERE geo_lat=$mLat AND geo_lng=$mLng");
if (!$results) {
header('HTTP/1.1 500 Error: Could not delete Marker!');
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);*/
$mpid = filter_var($_POST["propid"], FILTER_SANITIZE_STRING);
$results = $mysqli->query("INSERT INTO tblmarkers (geo_name, geo_address, geo_lat, geo_lng, prop_id) VALUES ('$mName','$mAddress',$mLat, $mLng, '$mpid')");
/* $results = $mysqli->query("INSERT INTO tblmarkers (geo_name, geo_address, geo_lat, geo_lng, geo_type, prop_id) VALUES ('$mName','$mAddress',$mLat, $mLng, '$mType', '$mpid')");*/
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 tblmarkers 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("geo_name",$obj->name);
$newnode->setAttribute("geo_address", $obj->address);
$newnode->setAttribute("geo_lat", $obj->lat);
$newnode->setAttribute("geo_lng", $obj->lng);
$newnode->setAttribute("geo_type", $obj->type);
}
echo $dom->saveXML();
Try this :
google.maps.event.addListener(map, "rightclick",function(event){
marker = new google.maps.Marker({
position: event.latLng,
title: 'Changer la position',
map: map,
draggable: true
});
this is an example : http://jsfiddle.net/hweb/M7K4L/
One option:
declare the marker globally (outside of any function definition):
var marker = null;
check to see if it exists, if it does delete it before creating one at the new location:
function create_marker(MapPos, MapTitle, MapDesc, InfoOpenDefault, DragAble, Removable, iconPath) {
if ((marker != null) && marker.setMap) {
marker.setMap(null);
marker = null;
}
//new marker
marker = new google.maps.Marker({
position: MapPos,
map: map,
draggable: DragAble,
animation: google.maps.Animation.DROP,
title: "Hello World!",
icon: iconPath
});
working fiddle
I am trying to make connection with my database
$.ajax({
url: 'pictures.php', data: "", dataType: 'json', success: function (rows) {
for (var i in rows) {
var row = rows[i];
var id = row[0];
var name = row[1];
var pic = row[2];
var lat = row[3];
var lon = row[4];
$(addMarker( id + name + pic + lat + lon));
}
}
});
This is pictures.php:
<?php
$dbname = 'test'; //Name of the database
$dbuser = 'root'; //Username for the db
$dbpass = ''; //Password for the db
$dbserver = 'localhost'; //Name of the mysql server
$dbcnx = mysql_connect("$dbserver", "$dbuser", "$dbpass");
mysql_select_db("$dbname") or die(mysql_error());
$query = mysql_query("SELECT * FROM bezienswaardigheden");
$data = array();
while ( $row = mysql_fetch_row($query) )
{
$data[] = $row;
}
echo json_encode( $data );
exit
?>
This is the function addMarker:
function addMarker(lat, lng, info) {
var pt = new google.maps.LatLng(lat, lng);
bounds.extend(pt);
var marker = new google.maps.Marker({
position: pt,
icon: icon,
map: map
});
var popup = new google.maps.InfoWindow({
content: info,
maxWidth: 300
});
google.maps.event.addListener(marker, "click", function () {
if (currentPopup != null) {
currentPopup.close();
currentPopup = null;
}
popup.open(map, marker);
currentPopup = popup;
});
google.maps.event.addListener(popup, "closeclick", function () {
map.panTo(center);
currentPopup = null;
});
}
I cant see markers on google maps with this code. The maps works perfect, but I want markers for places I fill in the database :( AJAX don't make connect with pictures.php.
This is javascript function to access latitude longitude and city from json:
function parse()
{
var json = '<?php echo $json; ?>';
var events = jQuery.parseJSON(json);
var DateArray = new Array();
var size = Object.keys(events).length;
search(events);
}
function search(events)
{
for ( i in events)
{
if( typeof events[i] === 'object' )
{
key= i.toLowerCase();
if(key.indexOf("latitude") !== -1)
{
var lat = events[i];
var longi = events['longitude'];
// alert(lat + longi);
initialize(lat,longi,'5');
// DateArray = DateArray.concat(events[i]);
// alert('DataArray');
}
search(events[i]);
}
}
}
I have this json:
{
"type":"http://schema.org/Place",
"class":"place",
"city":"London",
"geo":{
"type":"http://schema.org/GeoCoordinates",
"class":"geocoordinates",
"latitude":"30",
"longitude":"70"
}
}
map code:
function initialize(a,b,zom){
if (!a || !b ||!zom){
var centerLoc=new google.maps.LatLng( 34.61701054652337,71.37824736488983);
zoom=16;
}
else
{
alert(typeof a + typeof b + typeof zom);
var zoom =parseInt(zom);
var centerLoc=new google.maps.LatLng(a,b);
alert('it works fine');
}
var mapProp = {
center:centerLoc,
zoom:zoom,
//mapTypeId:google.maps.MapTypeId.ROADMAP
mapTypeId:google.maps.MapTypeId.SATELLITE
};
var map=new google.maps.Map(document.getElementById("googleMap") ,mapProp);
marker=new google.maps.Marker({
position:centerLoc,
title:'Click to zoom'
});
google.maps.event.addListener(marker,'click',function() {
map.setZoom(map.getZoom()+1);
map.setCenter(marker.getPosition());
});
marker.setMap(map);
}
google.maps.event.addDomListenerOnce(window, 'load', initialize);
When lat long and city are initialized, initialized function is called with lat and long as parameters.
problem
When arguments are passed to initialize function to initialize google map, it shows that function is called as it alerts the values of parameters in called function.lat and long both are string of type as required. but this does not show google map.