How to save a google maps marker data into mysql DB ? using php .
And is it possible to prevent dragging that marker out of a certain country ? or maybe validating if the data is out of the wanted country when clicking on submit for example.
Yes, no problem.
The database part, you will have to do yourself. I provide you 'ajax.php'; where you receive the POST data. All I do, is print the SQL-string.
The country is Belgium, feel free to change this (now on line 39). When ever the client drops the marker anywhere but in Belgium, the marker is sent back to the position where the client started dragging
ajax.php
<?php
if($_SERVER['REQUEST_METHOD'] === 'POST') {
$sql = "INSERT INTO markers (lat, lng) VALUES (". (float) $_POST['lat'] .", ". (float) $_POST['lng'] .");";
echo $sql;
}
?>
index.php
<div id="map-canvas"></div>
<div class="controls">
<input type="button" value="SAVE" id="save_marker">
</div>
<div id="display"></div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://maps.googleapis.com/maps/api/js?libraries=geometry&sensor=false"></script>
<script>
///////////////////////
// Ajax / upload part
$(document).ready(function() {
// initialize Google Maps
initialize();
// save marker to database
$('#save_marker').click(function() {
// we read the position of the marker and send it via AJAX
var position = marker.getPosition();
$.ajax({
url: 'ajax.php',
type: 'post',
data: {
lat: position.lat(),
lng: position.lng()
},
success: function(response) {
// we print the INSERT query to #display
$('#display').html(response);
}
});
});
});
///////////////////////
//Google Maps part
var map = null;
var marker = null;
var country = 'BE'; // Belgium. Feel free to use this script on any other country
// Google Maps
function initialize() {
var startDragPosition = null;
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(50.5, 4.5), // Over Belgium
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
// set the new marker
marker = new google.maps.Marker({
position: new google.maps.LatLng(50.5, 4.5),
map: map,
draggable: true
});
var myGeocoder = new google.maps.Geocoder();
// set a callback for the start and end of dragging
google.maps.event.addListener(marker,'dragstart',function(event) {
// we remember the position from which the marker started.
// If the marker is dropped in an other country, we will set the marker back to this position
startDragPosition = marker.getPosition();
});
google.maps.event.addListener(marker,'dragend',function(event) {
// now we have to see if the country is the right country.
myGeocoder.geocode({'latLng': marker.getPosition()}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK && results[1]) {
var countryMarker = addresComponent('country', results[1], true);
if (country != countryMarker) {
// we set the marker back
marker.setPosition(startDragPosition);
}
}
else {
// geocoder didn't find anything. So let's presume the position is invalid
marker.setPosition(startDragPosition);
}
});
});
}
/**
* geocodeResponse is an object full of address data.
* This function will "fish" for the right value
*
* example: type = 'postal_code' =>
* geocodeResponse.address_components[5].types[1] = 'postal_code'
* geocodeResponse.address_components[5].long_name = '1000'
*
* type = 'route' =>
* geocodeResponse.address_components[1].types[1] = 'route'
* geocodeResponse.address_components[1].long_name = 'Wetstraat'
*/
function addresComponent(type, geocodeResponse, shortName) {
for(var i=0; i < geocodeResponse.address_components.length; i++) {
for (var j=0; j < geocodeResponse.address_components[i].types.length; j++) {
if (geocodeResponse.address_components[i].types[j] == type) {
if (shortName) {
return geocodeResponse.address_components[i].short_name;
}
else {
return geocodeResponse.address_components[i].long_name;
}
}
}
}
return '';
}
</script>
<style>
#map-canvas {
height:400px;
}
</style>
Related
How do I add point when I click on google map?
So when I click on the map I want to add a pointer but I can not.
In this process, I take a LAT LANG value from the map and transfer it into an input. Then I fill out the required fields and fill out the form. But when I click on the map, it does not put a pointer.
JSFiddle: https://jsfiddle.net/Lzycb8c0/6/
JS Code:
var lat = 41.013995; //default latitude
var lng = 28.979741; //default longitude
var homeLatlng = new google.maps.LatLng(lat, lng); //set default coordinates
var homeMarker = new google.maps.Marker({ //set marker
position: homeLatlng, //set marker position equal to the default coordinates
map: map, //set map to be used by the marker
draggable: true //make the marker draggable
});
var geocoder = new google.maps.Geocoder;
var myOptions = {
center: new google.maps.LatLng(41.013995, 28.979741), //set map center
zoom: 17, //set zoom level to 17
mapTypeId: google.maps.MapTypeId.ROADMAP //set map type to road map
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions); //initialize the map
var marker = new google.maps.Marker({
draggable: true,
position: homeLatlng,
map: map,
title: "Your location"
});
google.maps.event.addListener(map, 'click', function (event) {
document.getElementById("lat").value = event.latLng.lat();
document.getElementById("long").value = event.latLng.lng();
// Reverse geo code using latLng
geocoder.geocode({'location': event.latLng }, function(results, status) {
if (status === 'OK') {
if (results[0]) {
$('#search_new_places').val( results[0].formatted_address );
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
});
//if the position of the marker changes set latitude and longitude to
//current position of the marker
google.maps.event.addListener(homeMarker, 'position_changed', function(){
var lat = homeMarker.getPosition().lat(); //set lat current latitude where the marker is plotted
var lng = homeMarker.getPosition().lng(); //set lat current longitude where the marker is plotted
});
//if the center of the map has changed
google.maps.event.addListener(map, 'center_changed', function(){
var lat = homeMarker.getPosition().lat(); //set lat to current latitude where the marker is plotted
var lng = homeMarker.getPosition().lng(); //set lng current latitude where the marker is plotted
draggable: true;
});
var input = document.getElementById('search_new_places'); //get element to use as input for autocomplete
var autocomplete = new google.maps.places.Autocomplete(input); //set it as the input for autocomplete
autocomplete.bindTo('bounds', map); //bias the results to the maps viewport
//executed when a place is selected from the search field
google.maps.event.addListener(autocomplete, 'place_changed', function(){
//get information about the selected place in the autocomplete text field
var place = autocomplete.getPlace();
if (place.geometry.viewport){ //for places within the default view port (continents, countries)
map.fitBounds(place.geometry.viewport); //set map center to the coordinates of the location
} else { //for places that are not on the default view port (cities, streets)
map.setCenter(place.geometry.location); //set map center to the coordinates of the location
map.setZoom(17); //set a custom zoom level of 17
}
homeMarker.setMap(map); //set the map to be used by the marker
homeMarker.setPosition(place.geometry.location); //plot marker into the coordinates of the location
});
$('#plot_marker').click(function(e){ //used for plotting the marker into the map if it doesn't exist already
e.preventDefault();
homeMarker.setMap(map); //set the map to be used by marker
homeMarker.setPosition(map.getCenter()); //set position of marker equal to the current center of the map
map.setZoom(17);
$('input[type=text], input[type=hidden]').val('');
});
$('#search_ex_places').blur(function(){//once the user has selected an existing place
var place = $(this).val();
//initialize values
var exists = 0;
var lat = 0;
var lng = 0;
$('#saved_places option').each(function(index){ //loop through the save places
var cur_place = $(this).data('place'); //current place description
//if current place in the loop is equal to the selected place
//then set the information to their respected fields
if(cur_place == place){
exists = 1;
$('#place_id').val($(this).data('id'));
lat = $(this).data('lat');
lng = $(this).data('lng');
$('#n_place').val($(this).data('place'));
$('#n_description').val($(this).data('description'));
$('#search_new_places').val($(this).data('kayitliyer'));
$('#n_yetkiliad').val($(this).data('yetkiliad'));
$('#n_magazaad').val($(this).data('magazaad'));
$('#n_telefon').val($(this).data('telefon'));
$('#y_telefon').val($(this).data('yetkilitelefon'));
$('#derece').val($(this).data('derece'));
}
});
if(exists == 0){//if the place doesn't exist then empty all the text fields and hidden fields
$('input[type=text], input[type=hidden]').val('');
}else{
//set the coordinates of the selected place
var position = new google.maps.LatLng(lat, lng);
//set marker position
homeMarker.setMap(map);
homeMarker.setPosition(position);
//set the center of the map
map.setCenter(homeMarker.getPosition());
map.setZoom(17);
}
});
});
You should add a create marker in your click listener
google.maps.event.addListener(map, 'click', function (event) {
document.getElementById("lat").value = event.latLng.lat();
document.getElementById("long").value = event.latLng.lng();
var newMarker = new google.maps.Marker({
draggable: true,
position: new google.maps.LatLng(event.latLng.lat(), event.latLng.lng()),
map: map,
title: "Your location"
});
// Reverse geo code using latLng
geocoder.geocode({'location': event.latLng }, function(results, status) {
if (status === 'OK') {
if (results[0]) {
$('#search_new_places').val( results[0].formatted_address );
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
});
Google geolocation with Javascript is not working in live site for major browsers like Firefox, Chrome. Geolocation result is displaying in Opera for live site, where as the same is working in localhost for all browsers (Chrome, firefox & Opera). My Live site protocol using https://. See below code and suggest any..
Geolocation and Google Maps API
<script src="http://maps.google.com/maps/api/js?key=MY_KEY_HERE&sensor=true"></script>
<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script>
function writeAddressName(latLng) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
"location": latLng
},
function(results, status) {
for (var i=0; i<results[0].address_components.length; i++) {
for (var b=0;b<results[0].address_components[i].types.length;b++) {
//there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
if (results[0].address_components[i].types[b] == "administrative_area_level_2") {
//this is the object you are looking for
city= results[0].address_components[i];
break;
}
}
}
//alert(city.short_name + " " + city.long_name);
//alert(city.long_name);
var cityname = city.long_name;
if (status == google.maps.GeocoderStatus.OK) {
document.getElementById("address").innerHTML = results[0].formatted_address;
document.getElementById("citynm").innerHTML = cityname; }
else {
document.getElementById("error").innerHTML += "Unable to retrieve your address" + "<br>"; }
});
}
function geolocationSuccess(position) {
var userLatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
// Write the formatted address
writeAddressName(userLatLng);
var myOptions = {
zoom : 16,
center : userLatLng,
mapTypeId : google.maps.MapTypeId.ROADMAP
};
// Draw the map
var mapObject = new google.maps.Map(document.getElementById("map"), myOptions);
// Place the marker
new google.maps.Marker({
map: mapObject,
position: userLatLng
});
// Draw a circle around the user position to have an idea of the current localization accuracy
var circle = new google.maps.Circle({
center: userLatLng,
radius: position.coords.accuracy,
map: mapObject,
fillColor: '#0000FF',
fillOpacity: 0.5,
strokeColor: '#0000FF',
strokeOpacity: 1.0
});
mapObject.fitBounds(circle.getBounds());
}
function geolocationError(positionError) {
document.getElementById("error").innerHTML += "Error: " + positionError.message + "<br>";
}
function geolocateUser() {
// If the browser supports the Geolocation API
if (navigator.geolocation)
{
var positionOptions = {
enableHighAccuracy: true,
timeout: 10 * 1000 // 10 seconds
};
navigator.geolocation.getCurrentPosition(geolocationSuccess, geolocationError, positionOptions);
}
else
document.getElementById("error").innerHTML += "Your browser doesn't support the Geolocation API";
}
window.onload = geolocateUser;
</script>
</head>
<body>
<p id="citynm"></p>
<p id="address"></p>
</body>
</html>
I have tested you codes (Chrome v29, Windows 8), the one below works from a remote server (non-local host) but you need note note 2 areas
<script src="http://maps.google.com/maps/api/js?v=3.9&sensor=true"></script>
I added v=3.9
And
function writeAddressName(latLng) {
...
if (results[0].address_components[i].types[b] == "route") {
You may need to handle case where city cannot be set.
I can see the address. [This sample does not include map display]
<!DOCTYPE html>
<html>
<head>
<script src="http://maps.google.com/maps/api/js?v=3.9&sensor=true"></script>
<script>
function writeAddressName(latLng) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ "location": latLng }, function(results, status) {
for (var i=0; i<results[0].address_components.length; i++) {
for (var b=0;b<results[0].address_components[i].types.length;b++) {
//there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
if (results[0].address_components[i].types[b] == "route") {
//this is the object you are looking for
city = results[0].address_components[i];
break;
}
}
}
//alert(city.short_name + " " + city.long_name);
//alert(city.long_name);
var cityname = city.long_name;
if (status == google.maps.GeocoderStatus.OK) {
document.getElementById("address").innerHTML = results[0].formatted_address;
document.getElementById("citynm").innerHTML = cityname;
}
else {
document.getElementById("error").innerHTML += "Unable to retrieve your address" + "<br>";
}
});
}
function geolocationSuccess(position) {
var userLatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
// Write the formatted address
writeAddressName(userLatLng);
var myOptions = {
zoom : 16,
center : userLatLng,
mapTypeId : google.maps.MapTypeId.ROADMAP
};
// Draw the map
var mapObject = new google.maps.Map(document.getElementById("map"), myOptions);
// Place the marker
new google.maps.Marker({
map: mapObject,
position: userLatLng
});
// Draw a circle around the user position to have an idea of the current localization accuracy
var circle = new google.maps.Circle({
center: userLatLng,
radius: position.coords.accuracy,
map: mapObject,
fillColor: '#0000FF',
fillOpacity: 0.5,
strokeColor: '#0000FF',
strokeOpacity: 1.0
});
mapObject.fitBounds(circle.getBounds());
}
function geolocationError(positionError) {
document.getElementById("error").innerHTML += "Error: " + positionError.message + "<br>";
}
function geolocateUser() {
// If the browser supports the Geolocation API
if (navigator.geolocation) {
var positionOptions = {
enableHighAccuracy: true,
timeout: 10 * 1000 // 10 seconds
};
navigator.geolocation.getCurrentPosition(geolocationSuccess, geolocationError, positionOptions);
}
else
document.getElementById("error").innerHTML += "Your browser doesn't support the Geolocation API";
}
window.onload = geolocateUser;
</script>
</head>
<body>
<p id="error"></p>
<p id="citynm"></p>
<p id="address"></p>
</body>
</html>
May be this links can help you
https://developers.google.com/maps/articles/geocodestrat
google maps api works at localhost but doesn't work at web server
https://developers.google.com/maps/faq?hl=en&csw=1#browsersupport
https://developers.google.com/maps/documentation/javascript/examples/map-geolocation
http://jsfiddle.net/BQzLq/3/
https://support.google.com/maps/answer/21849?hl=en
http://www.javascript-coder.com/window-popup/javascript-window-open.phtml
These all links is just for your knowledge in some browser or browser's older versions google map v3 doesn't works.
Actually I working on a website where user can add his business. And I want to give him a functionality to add any location on a map. As he saves his business details along with that map details should go to database so that after posting his business on website it should show that location on a map. In short, I want to allow the user to add his location on a map and on a website for that specific user map should show his location on a map.
As I am new to all this I am getting confused how to do this. So please help me out. I searched for it on google but I am not getting any help for my problem.
Thanks in advance....
Here is my tried code:
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(-33.8688, 151.2195),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var input = /** #type {HTMLInputElement} */(document.getElementById('searchTextField'));
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: map
});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
infowindow.close();
marker.setVisible(false);
input.className = '';
var place = autocomplete.getPlace();
if (!place.geometry) {
// Inform the user that the place was not found and return.
input.className = 'notfound';
return;
}
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17); // Why 17? Because it looks good.
}
marker.setIcon(/** #type {google.maps.Icon} */({
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(35, 35)
}));
marker.setPosition(place.geometry.location);
marker.setVisible(true);
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
var place = autocomplete.getPlace();
document.getElementById('city2').value = place.name;
document.getElementById('cityLat').value = place.geometry.location.lat();
document.getElementById('cityLng').value = place.geometry.location.lng();
var latitude = place.geometry.location.lat();
var longitude = place.geometry.location.lng();
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
infowindow.open(map, marker);
});
// Sets a listener on a radio button to change the filter type on Places
// Autocomplete.
function setupClickListener(id, types) {
var radioButton = document.getElementById(id);
google.maps.event.addDomListener(radioButton, 'click', function() {
autocomplete.setTypes(types);
});
}
setupClickListener('changetype-all', []);
setupClickListener('changetype-establishment', ['establishment']);
setupClickListener('changetype-geocode', ['geocode']);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<style>
#map-canvas, #map_canvas {
height: 400px;
width: 900px;
}
#media print {
#map-canvas, #map_canvas {
height: 400px;
width: 900px;
}
}
</style>
</head>
<body>
<?php
/*
* Smarty plugin
* -------------------------------------------------------------
* File: function.map.php
* Type: map
* Name: Map
* Purpose: Accept the keyword & find it on a map.
* -------------------------------------------------------------
*/
function smarty_function_map($params, &$smarty)
{
?>
<div id="panel">
<label>Location/Area*</label><input id="searchTextField" type="text" size="50" placeholder="Enter Location/Area">
<input type="text" id="city2" name="city2" />
<input type="text" id="cityLat" name="cityLat" />
<input type="text" id="cityLng" name="cityLng" />
</div>
<div id="map-canvas"></div>
<?php
}
?>
</body>
</html>
To allow users to add a marker to the map by clicking on it, you'll need to setup an event listener that will listen for any clicks on the map. Example:
var marker;
google.maps.event.addListener(map, 'click', function(event) {
if ( marker ) {
marker.setPosition(event.latLng);
} else {
marker = new google.maps.Marker({
position: event.latLng,
map: map,
draggable:true
});
}
});
You'll also want to enable the user to drag the marker after they've plotted it. You can do this by setting the marker to draggable (I did this in the above example). You'll also need to listen for any changes by attaching an event listener to the marker in question:
google.maps.event.addListener(marker, 'dragend', function(){
//Do something because marker has been dragged somewhere...
});
Finally, every time the map is clicked or a marker is dragged, you'll need to save the resulting latitude and longitude values in a hidden field(s) so that you can save the position in your database.
I am using gmap3 plugin to show google map. In my case I have stored all the information of properties in the database(mysql) with custom markers. Now I want that when the page is loaded it will display all the markers in google map.
For loading googlemap with gmap3 plugin I am using this code
function loadMap() {
jQuery(document).ready(function(){
if(typeof gMap == 'undefined') {
//// CREATES A MAP
gMap = jQuery('#map-canvas');
gMap.gmap3({
map: {
options: {
zoom: 2,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
navigationControl: true,
scrollwheel: true,
streetViewControl: false
}
}
});
}
});
}
and inside div ``map-canvas I can see the map. But can some one kindly tell me how to show all the markers with the positions? Any help and suggestions will be really appreciable. Thanks.
Update
If I am wrong with my codes then someone can show their codes to me. I am using Gmap3 plugin.
I am not sure about this it will work in gmap3 but i use this code for creating my costome icon hope it will help you
In the index.php use this for creating your costom icon pathlike this
<?php
$query = "SELECT * FROM markers WHERE 1";
$result = mysql_query($query);
$a=array();
while ($row = #mysql_fetch_assoc($result)){ $a='$row[\'type\']'=>array('icon'=>'$row[\'path\']','shadow'=>'$row[\'path2\']')
}
$a=json_encode($a);
?>
it should be done before js file after that
write this
<script>
var customIcons= <?php echo $a; ?>;
</script>
and finally load your map and infoWindowbox() in that function
function infoWindowbox() {
downloadUrl("xml.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> <br/>" + address;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow,
animation: google.maps.Animation.DROP
});
markerArray.push(marker);
bounds.extend(marker.position);
bindInfoWindow(marker, map, infoWindow, html);
}
map.fitBounds(bounds);
// var markerCluster = new MarkerClusterer(map, markerArray);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
gmap3 initializator has a marker attribute that allows you to create markers.
See example with single and multiple markers here:
http://gmap3.net/en/catalog/10-overlays/marker-41
I think this example might help.
Updated:
If you want to read the data like from database (or) xml, You can then make an ajax request to that page (from any page on your site) using jQuery:
I have an example but this is with xml to get the data from xml file.
$.ajax({
url: 'categories.xml (or) your database path',
type: 'get',
success: function(doc) {
var xmlDoc = GXml.parse(doc);
var markers = xmlDoc.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"));
var point = new GLatLng(lat,lng);
var address = markers[i].getAttribute("address");
var name = markers[i].getAttribute("name");
var html = "<b>"+name+"<\/b><p>"+address;
var category = markers[i].getAttribute("category");
// create the marker
var marker = createMarker(point,name,html,category);
map.addOverlay(marker);
}
// == show or hide the categories initially ==
show("theatre");
hide("golf");
hide("info");
// == create the initial sidebar ==
makeSidebar();
});
});
Like this you may get the data from database also through using queries. Try this one atleast you may get the idea.
The gmaps3 plugin documentation shows how to add markers. If you create an options array in php through ajax/json and feed that to the markers: option your markers should be added.
hopefully you can help me. I have read a lot of forums regarding this but still cannot get what I wanted. I'm using PHP/MySQL to run my system. I already had a code in JavaScript that will allow the user to add a place and the system can add that place in the Google Map (embedded in my site) as a marker. Now, what I wanted is to add the coordinates of that new place in my database and then my map will just get the markers from the database for adding in the map.
Currently, what I did is to get the latitude and longitude of the added place from the javascript then was able to pass them to my php script within the same file. The latitude and longitude can be added in my database but I do not know now how to go back again to JavaScript so that I can add my markers.
What is the best way to do this? Is/Are there better approaches to solve this?
<?php
$marker = array();
if(isset($_GET['set'])){
$lat = $_GET['lat'];
$long = $_GET['longi'];
$newadd = $_GET['newAdd'];
$connect = mysql_connect("localhost","root","");
mysql_select_db("mapping");
$query=mysql_query("INSERT INTO markers VALUES('','','$newadd','$lat','$long','')");
}
?>
My JavaScript to place markers
function addMarkers(){
var tempMarker;
var tabs = [];
var blueIcon = new GIcon(G_DEFAULT_ICON);
blueIcon.image = "http://maps.google.com/mapfiles/ms/micons/green-dot.png";
// Set up our GMarkerOptions object
markerOptions = { icon:blueIcon };
// for loop get data from db and loop it
tempMarker = new GMarker(tempLatLng,markerOptions);
//if(tabs.length==0){
tabs[ctr] = [new GInfoWindowTab('Greetings','Hi! Welcome'), new GInfoWindowTab('My Info',tempMarker.getLatLng().toString())];
//}
tabInfoWindow(tempMarker,tabs, ctr);
markerArray.push(tempMarker);
displayMarkers();
}
}
Thanks!
Using jquery you can post the data in an ajax request and continue adding the markers in the success handler.
var location = {lat:56, lng:67, name:"my_place"};
$.ajax({
url: "save_place.php",
data: location,
dataType:"json",
success: function(response){
if(response.success){
// add marker to map here
}else{
alert("Error adding location to database");
}
},
error:function(){
alert("Error in connecting to server");
}
});
EDIT:
From your comments, I understand what you need is this one:
<?php
$lat = isset($_GET['lat']) ? $_GET['lat'] : 0;
$long = isset($_GET['longi']) ? $_GET['longi'] : 0;
$newadd = isset($_GET['newAdd']) ? $_GET['newAdd'] : "";
?>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type='text/javascript' src="http://maps.google.com/maps/api/js?sensor=false&.js"></script>
<style type='text/css'>
#map {
width: 400px;
height: 400px;
}
</style>
</head>
<body>
<div id="map"></div>
<script type='text/javascript'>//<![CDATA[
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: new google.maps.LatLng(55, 11),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
function addMarker(lat, lng, newAdd) {
alert(" Adding marker " + lat + "," + lng);
this.lat = lat;
this.long = lng;
var location = new google.maps.LatLng(lat, long);
var marker = new google.maps.Marker({
position: location,
title: name,
map: map,
draggable: true
});
map.setCenter(location);
}
<?php
echo "addMarker($lat, $long, '$newadd')";
?>
</script>
</body>
</html>
url : http://<domain>/test.php?lat=40.735812&longi=-74.001389&newAdd=
Well what I do is have a endpoint on the PHP side that I can ask for the markers. Then when my map has loaded I will make a call to get them and then add them on:
$.post('/server/getMarkers',{},function(markers) {
for(var i=0; i < markers.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(marker[i].latitude, marker[i].longitude),
id:marker[i].id
});
google.maps.event.addListener(marker, "click", function() {
//request data for this.id to show in info window if needed
});
}
});
The getMarkers method on the PHP side could look something like this
public function getMarkers() {
/* fetch an array of markers details from the db by any means... */
$markers = getMarkersFromDB();
foreach ($markers as $key=> $marker) {
$payload[$key]['latitude'] = $marker->latitude;
$payload[$key]['longitude'] = $marker->longitude;
$payload[$key]['id'] = $marker->id;
}
echo json_encode($payload);
}