I want to insert a link inside inside the JavaScript.
I want this link infoWindow.setContent('Adaugă sesizare pentru locația ta actuală .');
to send the user to add-sesizare.php?lat=&lng=&userid=
<?php include 'header.php';
session_start();
if (isset($_SESSION['user'])) {
$email = $_SESSION['user'];
$query = "SELECT * FROM useri WHERE email='$email' LIMIT 1";
$result = mysqli_query($con,$query);
$user = mysqli_fetch_assoc($result);
$userid = $user['id'];
} else { header('Location: login.php'); }
?>
<div class="head-first">
<div class="d-flex justify-content-between">
<a class="navbar-brand" href="#">
<i class="fas fa-users"></i> MyCity Curtici
</a>
<span style="font-size:30px;cursor:pointer;padding: 0 0 0 15px;" onclick="openNav()">☰</span>
</div>
</div>
<div id="map"></div>
<script>
// Note: This example requires that you consent to location sharing when
// prompted by your browser. If you see the error "The Geolocation service
// failed.", it means you probably did not give permission for the browser to
// locate you.
var map, infoWindow;
var user_id = "<?php echo $userid ?>";
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 46.35, lng: 21.3},
zoom: 15
});
infoWindow = new google.maps.InfoWindow;
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Adaugă sesizare pentru locația ta actuală .');
infoWindow.open(map);
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
google.maps.event.addListener(map, 'click', function(event) {
window.location='add-sesizare.php?lat='+event.latLng.lat()+'&long='+event.latLng.lng()+'&userid='+user_id;
});
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
infoWindow.open(map);
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDd7JYEWDAJVdVkIzZOQumCHYbS2xsIvtM&callback=initMap"
async defer></script>
<?php include 'footer.php' ?>
You have an issue with your ' vs. ", and you don't have any attempt to add the local values of lat/lng returned by the geolocation service (which I assume is needed).
infoWindow.setContent('Adaugă sesizare pentru locația ta actuală .');
(uses ' for the javascript string, " for the quoting in HTML.)
proof of concept fiddle
code snippet:
// Note: This example requires that you consent to location sharing when
// prompted by your browser. If you see the error "The Geolocation service
// failed.", it means you probably did not give permission for the browser to
// locate you.
var map, infoWindow;
var user_id = "$userid";
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 46.35,
lng: 21.3
},
zoom: 15
});
infoWindow = new google.maps.InfoWindow;
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Adaugă sesizare pentru locația ta actuală .');
infoWindow.open(map);
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
google.maps.event.addListener(map, 'click', function(event) {
window.location = 'add-sesizare.php?lat=' + event.latLng.lat() + '&long=' + event.latLng.lng() + '&userid=' + user_id;
});
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
infoWindow.open(map);
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap"></script>
Related
I have a map code like this:
function initMap() {
var map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 7,
center: new google.maps.LatLng(52.215594, 21.014130),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var myMarker = new google.maps.Marker({
position: new google.maps.LatLng(52.215594, 21.014130),
draggable: true
});
google.maps.event.addListener(myMarker, 'dragend', function(evt) {
document.getElementById('current').innerHTML = '<p>Marker dropped: Current Lat: ' +
evt.latLng.lat().toFixed(6) + ' Current Lng: ' + evt.latLng.lng().toFixed(6) + '</p>';
});
google.maps.event.addListener(myMarker, 'dragstart', function(evt) {
document.getElementById('current').innerHTML = '<p>Moving marker...</p>';
});
map.setCenter(myMarker.position);
myMarker.setMap(map);
}
I want to save the lat and lng values to the database but I don't know how to get them, I just know how to display lat and lng in js. The marker has draggable option. I can drag it to the desired location on the map and then show the dragged data of this marker (lat and lng) will be displayed by innerHTML.
But how now to get these values (lat and lng) after dragging them to desired position and save them to the database? My site is written in Smarty. Thank you in advance for your help.
It is easy enough to add your own ajax function within the dragend callback to fire-off a HTTPRequest that can be used to save the lat/lng of the current marker position.
The following uses fetch in conjunction with FormData to create and send the request. In this example the request is processed by the same page but you can simply change the javascript endpoint variable to point to a separate PHP script to save the lat/lng.
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && isset(
$_POST['lat'],
$_POST['lng']
)){
/* save to db */
$sql='insert into `markers` (`lat`,`lng`) values (?,?)';
# $stmt=$db->prepare($sql);
# $stmt->bind_param('ss',$_POST['lat'],$_POST['lng']);
# $stmt->execute();
#etc
#prepare data to send back if appropriate
$data=array(
'status'=> 'success',
'lat' => $_POST['lat'],
'lng' => $_POST['lng'],
'sql' => $sql,
'date' => date( DATE_ATOM ),
'ip' => $_SERVER['REMOTE_ADDR']
);
# send data and exit
exit( json_encode( $data ) );
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<style>
body, body *{
box-sizing:border-box;
}
#map{
width:800px;
height:600px;
float:none;
margin:auto;
}
#current{
width:800px;
float:none;
margin:1rem auto;
}
</style>
<script>
function initMap() {
let lat=52.215594;
let lng=21.014130;
const current=document.getElementById('current');
const savelatlng=(e)=>{
let fd=new FormData();
fd.set('lat',e.latLng.lat());
fd.set('lng',e.latLng.lng());
let endpoint=location.href; // the php script that will save the latlng
fetch( endpoint, { method:'post', body:fd })
.then(r=>r.json())
.then(json=>{
console.log( 'Position saved: %o', json )
});
};
var map=new google.maps.Map(document.getElementById('map'), {
zoom:7,
center:new google.maps.LatLng( lat, lng ),
mapTypeId:google.maps.MapTypeId.ROADMAP
});
var myMarker=new google.maps.Marker({
draggable:true,
map:map
});
myMarker.setPosition( map.getCenter() );
google.maps.event.addListener( myMarker, 'dragend', function( evt ) {
current.innerHTML = `<p>Marker dropped: Current Lat: ${evt.latLng.lat().toFixed(6)} Current Lng: ${evt.latLng.lng().toFixed(6)}</p>`;
map.setCenter( evt.latLng );
savelatlng( evt );
});
google.maps.event.addListener( myMarker, 'dragstart', function( evt ) {
current.innerHTML = '<p>Moving marker...</p>';
});
}
</script>
<script async defer src='//maps.googleapis.com/maps/api/js?key=<APIKEY>&callback=initMap'></script>
</head>
<body>
<div id='map'></div>
<div id='current'></div>
</body>
</html>
Been having a lot of dificulties to send geolocation data to php for store after in mysql. Searching and getting support has achieved a lot but still doesn't see the coords of the users in page.
Here the code.
1.code from template-maps.php:
var pos;
var posZae = function(pos){
return {
coords: {
latitude: pos.coords.latitude,
longitude: pos.coords.longitude,
accuracy: pos.coords.accuracy.toFixed()
},
timestamp: pos.timestamp
}
};
var netPOS;
var infoWindow = new google.maps.InfoWindow({map: map});
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('You are here');
map.setCenter(pos);
var netPOS = JSON.stringify(posZae(position));
$.ajax({
type: 'POST',
data: { 'pos' : pos},
url: '/wp-content/themes/honolulu/template-userslocation.php'
});
},
function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
};
it should send the data to template-userslocation.phpwhere I have this code:
<?php
/**
* Template Name: template-userslocation
*/
$lat = isset($_POST['pos']['lat']) ? $_POST['pos']['lat'] : null;
$lng = isset($_POST['pos']['lng']) ? $_POST['pos']['lng'] : null;
?>
I get no ERROR, but if I charge the page there is no data. Nothing in the page and in the console.
Solved:
The problem is that it is being made in Wordpress and Wordpress has his own way to handle AJAX.
Here the info
EDIT 2
I have no idea about any WordPress plugins or PHP. Does the lat/lng appear on the network/at the server? Anyway try this: -
var posZae = function(pos){
return {
lat: pos.coords.latitude,
lng: pos.coords.longitude,
}
};
var infoWindow = new google.maps.InfoWindow({map: map});
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = posZae(position);
var netPOS = JSON.stringify(pos);
infoWindow.setPosition(pos);
infoWindow.setContent('You are here');
map.setCenter(pos);
$.ajax({
type: 'POST',
data: { 'pos' : netPos},
url: '/wp-content/themes/honolulu/template-userslocation.php'
});
},
function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
};
EDIT 1
OK would this ring any bells of familiarity with you?
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('You are here');
map.setCenter(pos);
var netPOS = JSON.stringify(pos4Net(position));
$.ajax({
type: 'POST',
data: { 'pos' : netPOS},
url: '/wp-content/themes/atripby/template-userslocation.php'
});
ORIGINAL POST:
Not sure where you "pos" is declared. Maybe localizing it with VAR will help instantiate it?
I've had the same/similar problem with the nature of the position object and call the following before trying to transmit it over the network: -
var pos4Net =
function(pos)
{
return {
coords: {
latitude: pos.coords.latitude,
longitude: pos.coords.longitude,
accuracy: pos.coords.accuracy.toFixed()
},
timestamp: pos.timestamp
}
}
So var yourPos = pos4Net(position)
there is no data. Nothing in the page and in the console.
Your PHP code copies the POSTed data into a couple of variables. That is all.
It doesn't output anything. It doesn't use the variables for anything.
It just stores in the data in variables, then exits (which destroys the variables because they only exist for the lifetime of the program execution).
You need to do something with the data.
You could just output it straight back:
<?php header("Content-Type: text/plain"); echo $lat; echo $lng; ?>
… which isn't very useful, but serves as a demonstration.
Your JavaScript does nothing with the response.
(The response, as mentioned above, doesn't contain anything, so you need to fix the PHP first).
You have no success handler in your JavaScript, so when the browser gets the response, your code doesn't do anything with it. This is why nothing is shown in the browser.
url: '/wp-content/themes/atripby/template-userslocation.php'
}).done(function(data) { console.log(data); });
… would show the results in the browser's developer tools console.
first console your lat. and lang. to check if you get any result then use the following code in ajax
data: { 'lang' : coordinates , 'lat': coordinate},
then use $_POST['lant'] and $_POST['lang'] in destination file
The ajax function is sending pos which is an object but you are using array notation within the php script to access the lat/lng.
Perhaps if you did
$.ajax({
type: 'POST',
data: { lat:pos.lat, lng:pos.lng },
url: '/wp-content/themes/atripby/template-userslocation.php'
});
You could then, in the PHP, try
$lat=!empty( $_POST['lat'] ) ? $_POST['lat'] : null;
$lng=!empty( $_POST['lng'] ) ? $_POST['lng'] : null;
Image of current functionality
Hi I'm using the 'xdsoft datetimepicker jquery plugin' (http://xdsoft.net/jqplugins/datetimepicker/) within my application so the user can select a date/time of arrival to a set destination.
Currently my application is using Google's Javascript API & lets the user toggle between 2 travel modes - either Transit or Driving (As seen in the image I've uploaded above)
Google Javascript API Request:
directionsService.route({
origin: pos,
destination: {lat: *Value*,lng: *Value*},
travelMode: google.maps.TravelMode[selectedMode],
transitOptions: {
modes: ['RAIL'],
**************
arrivalTime: new Date(), <<< *** WHERE I NEED TO PASS DATE/TIME PICKER VALUE
**************
routingPreference: 'FEWER_TRANSFERS'
},
unitSystem: google.maps.UnitSystem.IMPERIAL,
provideRouteAlternatives: true
}, function(response, status) {
if (status == 'OK') {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
I'm not sure how to pass the date/time value from the picker into 'arrivalTime: new Date()' in the API request as an epoch timestamp in milliseconds, so that directions are returned based on date/time the user has selected and update each time this is changed. Obviously as default, without a date specified Google API returns directions for the current time.
HTML for Date/Time Picker:
<div id="timepicker">
<input id="datetimepicker" type="text" >
</div>
Javascript for Date/Time Picker:
jQuery('#datetimepicker').datetimepicker({
format:'d.m.Y H:i',
defaultTime:'15:00'
});
Full script for my API request to toggle between travel modes and update map without letting the user specify an arrival time from the datetimepicker:
<script>
function initMap() {
var directionsDisplay = new google.maps.DirectionsRenderer;
var directionsService = new google.maps.DirectionsService;
var lattp = <?php echo json_encode($lattp);?>;
var lngtp = <?php echo json_encode($lngtp);?>;
var zoomtp = <?php echo json_encode($zoomtp);?>;
var tp = {lat: JSON.parse(lattp), lng: JSON.parse(lngtp)};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 14,
center: tp
});
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('right-panel'));
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
document.getElementsByName('radio').forEach(function(el){
el.addEventListener('click', function() {
calculateAndDisplayRoute(directionsService, directionsDisplay, pos);
});
})
calculateAndDisplayRoute(directionsService, directionsDisplay, pos);
}, function() {
handleLocationError(true, markerme);
});
} else {
// Browser doesn't support Geolocation
window.alert('Geolocation is not supported');
}
}
function calculateAndDisplayRoute(directionsService, directionsDisplay, pos) {
//var selectedMode = document.getElementById('mode').value;
var selectedMode = "";
var radios = document.getElementsByName('radio')
radios.forEach(function(element) {
if(element.checked){
selectedMode = element.value;
}
})
directionsService.route({
origin: pos,
destination: {lat: *Value*,lng: *Value*},
travelMode: google.maps.TravelMode[selectedMode],
transitOptions: {
modes: ['RAIL'],
arrivalTime: new Date(),
routingPreference: 'FEWER_TRANSFERS'
},
unitSystem: google.maps.UnitSystem.IMPERIAL,
provideRouteAlternatives: true
}, function(response, status) {
if (status == 'OK') {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
</script>
Thanks in advance for any help given - appreciate it!
Your formatted input box is already one that a constructor to Date can parse. Just pass in the value of your input box:
startDate = new Date(jquery('#datetimepicker').val());
So I'm still relatively new to Meteor, and this will be my first Meteor project using an external API, and I'm running into a few issues. I've made web apps using the maps api before, and have had no problem displaying directions, but for some reason I'm having a lot of issue with Meteor. I have no problem getting the map to actually display a users current position, and map styling is the way I want it, but when it comes to the part where the user inputs directions, nothing happens. The map doesn't update, and I'm left just staring at the the current location. I'm using the packages jeremy:geocomplete dburles:google-maps and mdg:geolocation.
Here are the templates which create the map, and take user input for the destination:
<template name="map">
<div class="map-container">
{{#unless geolocationError}}
{{> googleMap name="map" options=mapOptions}}
{{else}}
Geolocation failed: {{geolocationError}}
{{/unless}}
</div>
</template>
<template name="greeting">
<div class="greet-overlay">
<div class="greet-window">
<div class="splash-window">
<p class="splash-text">Text</p>
<img class="splash" src="splash/PClogo.png" alt="Lorem Ipsum">
{{> addressForm}}
</div>
</div>
</div>
</template>
<template name="addressForm">
<div class="form-window">
<img src="game/directions.png" id="stuff">
<h1 class="address-title">Enter Destination</h1>
<input type="text" id="address" name="text" />
<button>Submit</button>
</div>
</template>
And here are the events and helpers for those templates (leaving out all the geocode stuff for now):
Template.map.helpers({
geolocationError: function() {
var error = Geolocation.error();
return error && error.message;
},
mapOptions: function() {
var latLng = Geolocation.latLng();
// Initialize the map once we have the latLng.
if (GoogleMaps.loaded() && latLng) {
return {
center: new google.maps.LatLng(LAT, LNG),
zoom: MAP_ZOOM
};
}
}
});
Template.map.onCreated(function() {
map = GoogleMaps.ready('map', function(map) {
var latLng = Geolocation.latLng();
var marker = new google.maps.Marker({
position: new google.maps.LatLng(LAT, LNG),
map: map.instance,
icon: '/game/loc_marker.png'
});
});
});
Template.addressForm.onRendered(function() {
this.autorun(function () {
if (GoogleMaps.loaded()) {
$("input").geocomplete()
.bind("geocode:result", function(event, result){
DESTLAT = result.geometry.location.lat();
DESTLNG = result.geometry.location.lng();
});
}
});
});
Template.addressForm.events({
'click button': function() {
directionsService = new google.maps.DirectionsService;
directionsDisplay = new google.maps.DirectionsRenderer;
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('panel'));
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
directionsService.route({
origin: LAT + ',' + LNG,
destination: DESTLAT + ',' + DESTLNG,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
console.log('Directions request failed due to ' + status);
}
});
}
calculateAndDisplayRoute(directionsService, directionsDisplay);
$(".greet-overlay").toggle();
}
});
So yeah, basically everything works exactly the way I want it to, except for the directions. Not even the status responses are being logged to the console. I have no doubt I'm doing something so utterly foolish here that it's going to make me seriously question my career choices. Mistakes are probably being made, and I will learn from them.
Figured it out after some toying around! So essentially all I had to do was move some stuff around as I was initializing some things in the wrong order. I moved thecalculateAndDisplayRoute function out of the addressForm event template, and swapped the contents of map.onCreated with addressForm.onRendered. Now it is structured something like this:
function calculateAndDisplayRoute(service, display) {
directionsService.route({
origin: LAT + ',' + LNG,
destination: DESTLAT + ',' + DESTLNG,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
console.log('Directions request failed due to ' + status);
}
});
}
emplate.map.helpers({
geolocationError: function() {
var error = Geolocation.error();
return error && error.message;
},
mapOptions: function() {
var latLng = Geolocation.latLng();
// Initialize the map once we have the latLng.
if (GoogleMaps.loaded() && latLng) {
return {
center: new google.maps.LatLng(LAT, LNG),
zoom: MAP_ZOOM,
};
}
}
});
Template.map.onCreated(function() {
this.autorun(function () {
if (GoogleMaps.loaded()) {
$("input").geocomplete()
.bind("geocode:result", function(event, result){
DESTLAT = result.geometry.location.lat();
DESTLNG = result.geometry.location.lng();
directionsService = new google.maps.DirectionsService;
directionsDisplay = new google.maps.DirectionsRenderer;
});
}
});
});
Template.addressForm.onRendered(function() {
GoogleMaps.ready('map', function(map) {
var latLng = Geolocation.latLng();
var marker = new google.maps.Marker({
position: new google.maps.LatLng(LAT, LNG),
map: map.instance,
icon: '/game/loc_marker.png'
});
});
});
Template.addressForm.events({
'click button': function() {
var map = GoogleMaps.maps.map.instance;
calculateAndDisplayRoute(directionsService, directionsDisplay);
directionsDisplay.setMap(map);
$(".greet-overlay").toggle();
}
});
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