Google Map - Take coordinates - php

I have google map on my site(php,apache,mysql).
here is code:
<script type="text/javascript">
function initialize() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map_canvas"));
var point = new GLatLng(<? $default_ll ?>,<? $default_spn ?>);
map.setCenter(point, 15);
map.setUIToDefault();
map.setMapType(G_NORMAL_MAP);
var marker = new GMarker(point);
map.addOverlay(marker);
}
}
window.onload = initialize;
window.onunload = GUnload;
</script>
<div id="map_canvas" style="width:500px;height:300px;"></div>
I want to make button(outside of map div), so when user chose hes coords and clicks this button. Current location he is watching rightnow will be put in to database. Well for simplicity can you show how to assign current: ll to $new_ll and spn to $new_spn

The GMap2 map object has these methods:
var center = map.getCenter(); // returns GLatLng of center point of map
var span = map.getBounds(); // returns GLatLngBounds of current map view
Using these simply you could have a button like this:
<input type="button" onclick="javascript:alert(map.getCenter())" value="Show Coordinates"/>
More realistically, you'll define a function to be called by the button's onclick:
function showCenterAndSpan()
{
var center = map.getCenter();
var span = map.getBounds();
var ne = span.getNorthEast();
var sw = span.getSouthWest();
var coordStr = "lat=" + center.lat() + "&lng=" + center.lng() +
"&n=" + ne.lat() + "&e=" + ne.lng() + "&s=" + sw.lat() + "&w=" + sw.lng();
alert(coordStr); // Or, post this string to the server to save into the database
}

Related

Getting current zoom level from a Google Map

I am using a google map in a PHP/MYSQL application. I get the code for the map form Goolge Docs and adapted a bit for the application.
New modifications are comming in the application and now the application need to know the 'current zoom level of the google map'. I check in internet but I didn't find a clear answer.
Is it possible to do it ? Is it mandatory to reload the page in every zoom change ?
This is the code and thanks.
<code>
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(latitude,longitude),
zoom: zoommapa,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE
},
mapTypeId: 'roadmap'
});
// drap center
var image = 'images/icons/etapa/etapa.png';
var myLatLng = new google.maps.LatLng(latitude,longitude);
var beachMarker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("marquers_motor_3.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
//var name = 1;
var markers2 = [];
for (var i = 0; i < markers.length; i++) {
//var name = markers[i].getAttribute("name");
var image = markers[i].getAttribute("image");
var sombra = markers[i].getAttribute("sombra");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var orden = markers[i].getAttribute("order");
var name = markers[i].getAttribute("name"); // web_site email ciudad pais
var web_site = markers[i].getAttribute("web_site");
var email = markers[i].getAttribute("email");
var ciudad = markers[i].getAttribute("ciudad");
var pais = markers[i].getAttribute("pais");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
if (ciudad =="" || ciudad =='Desconocido') { ciudad = ""} else {ciudad =ciudad + " " }
if (!(web_site =="")) {web_site = "<a href='" + web_site + "' class='list' target='_blank'>" + web_site +"</a>"+"<br>"} else {web_site =""}
var html = "<div id='infoWindow'>" + orden + " - " + name + "<br>" + web_site + ciudad + " " + pais + "</div>";
//var name = name + 1;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: image,
shadow: sombra
});
var marker2 = new google.maps.Marker({
position: point
});
markers2.push(marker);
bindInfoWindow(marker, map, infoWindow, html);
}
});
var mcOptions = {gridSize: 50, maxZoom: 15};
var MarkerClusterer = new MarkerClusterer(map, markers2,mcOptions);
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
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() {}
//]]>
//google.maps.event.addDomListener(window, 'load', initialize);
I assume the application needs to know the zoom level, but the zoom level is in user space (client side).
get the zoom level from the map with javascript (see https://developers.google.com/maps/documentation/javascript/reference?hl=nl#Map)
map.getZoom();
This has to be send back to the server using AJAX calls
Server can do with the zoom level what it wants
Keep in mind the fact that if multiple users can open the same map, zoom levels can be different so what would be the required behavior?
Yes, you can get the current zoom level of the map with the getZoom method of the google.maps.Map object.
If you need to trigger a method when the zoom changed then you can listen to the zoom_changed event of the google.maps.Map object. For further information about google.maps.Map object read: this
Consider the following example (to make it work: copy in notepad save the file as html and run it with Chrome):
<!DOCTYPE html>
<html>
<head>
<title>Getting Zoom Demo</title>
<style type="text/css">
html, body{ height: 100%; height: 100%; margin: 0; padding: 0; }
#map-container{ height: 100%; width: 100%; min-width:500px; min-height:300px; }
</style>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
</head>
<body>
<div>
<label id="display-zoom-label">
</label>
</div>
<div id="map-container"></div>
<script>
// Global map variable to have access to map object everywhere in the code
var map,
firstBoundChangedListener,
markers = [];
// Add random markers
function addMarkers(count) {
// map is the google.maps.Map object
var bounds = map.getBounds();
var northEast = bounds.getNorthEast();
var southWest = bounds.getSouthWest();
var minLat = Math.min(northEast.lat(), southWest.lat());
var maxLat = Math.max(northEast.lat(), southWest.lat());
var minLng = Math.min(northEast.lng(), southWest.lng());
var maxLng = Math.max(northEast.lng(), southWest.lng());
var latDifference = maxLat - minLat;
var lngDifference = maxLng - minLng;
var latLngArray = new Array();
for (var i = 0; i < count; i++) {
var lat = minLat + Math.random() * latDifference;
var lng = minLng + Math.random() * lngDifference;
var latLng = new google.maps.LatLng(lat, lng);
latLngArray.push(latLng);
}
for (var i = 0; i < latLngArray.length; i++) {
var marker = new google.maps.Marker({
position: latLngArray[i],
title: "Marker: " + i
});
markers.push(marker);
marker.setMap(map);
}
}
function UpdateZoomLabel() {
var displayZoomLabel = document.getElementById("display-zoom-label"),
// get current zoom
zoomValue = map.getZoom();
displayZoomLabel.innerHTML = "The Current Map's Zoom is: " + zoomValue;
}
// Initialize the map object
function initialize() {
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 8,
center: latlng
};
map = new google.maps.Map(document.getElementById('map-container'), mapOptions);
firstBoundChangedListener = google.maps.event.addListener(map, "bounds_changed", function () {
if (firstBoundChangedListener) google.maps.event.removeListener(firstBoundChangedListener);
// call add markers: add 'n' markers randomly
addMarkers(6);
});
//Listen for the 'zoom_changed' event of the map
google.maps.event.addListener(map, "zoom_changed", function () {
//show zoom in label
UpdateZoomLabel();
});
UpdateZoomLabel();
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</body>
</html>

Removing marker by latitude/longitude in google maps

I have set of markers in my google map. And at the right side of my map I have list of places marked in the map. Now upon clicking the places the color of the pin/marker should be changed. For this I thought I would delete the marker with latitude and longitude(which I will get on clicking the places link) and place a new marker with new image. But I dont know how to delete a marker with latitude and longitude or by place. Please help.
<script type='text/javascript'>
$(document).ready(function() {
var map = null;
var infowindow = new google.maps.InfoWindow();
function createMarker(place) {
var marker = new google.maps.Marker({
map: map
});
var address = place.formatted_address;
marker.setPosition(place.geometry.location);
marker.setTitle(address);
marker.setVisible(true);
address = address + 'B <a class="link" href="#" title="Want to go" alt="' + address + '">W</a> <a class="link" href="#" alt="' + address + '" title="Favourite">F</a>';
$('#trip_location').append(address);
google.maps.event.addListener(marker, 'click', function(e) {
infowindow.setContent('<div><strong>' + marker.title + '</strong><br>');
infowindow.open(map, marker);
});
google.maps.event.trigger(marker, 'click');
}
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(-33.8688, 151.2195),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
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);
google.maps.event.addListener(autocomplete, 'place_changed', function() {
infowindow.close();
input.className = '';
var place = autocomplete.getPlace();
if (!place.geometry) {
// Inform the user that the place was not found and return.
input.className = 'notfound';
return;
}
var location = place.geometry.location;
var address = place.formatted_address;
createMarker(place);
});
}
$('#trip_location').on('click', '.link', function(e) {
e.preventDefault();
var location = $(this).attr('alt');
});
$('.clear').click(function() {
$('#searchTextField').val('');
});
google.maps.event.addDomListener(window, 'load', initialize);
});
I will be adding multiple markers to google map through google's autocomplete. And the places of the markers will be listed on the right side of the page. When the user clicks the places, it should replace the marker icon.
Instead of deleting and replacing, you could keep a reference to each marker that is associated with a place and just call setIcon on it passing the new setting. See documentation: https://developers.google.com/maps/documentation/javascript/reference#Marker
EDIT: New code in question.
Added markers array to contain the markers, used data attribute to hold marker id, pull markerid attribute value when link element click event is fired.
NOTE: Not tested, so it may be buggy.
$(document).ready(function() {
var map = null;
var markers = [];
var infowindow = new google.maps.InfoWindow();
function createMarker(place) {
var marker = new google.maps.Marker({
map: map
});
var address = place.formatted_address;
marker.setPosition(place.geometry.location);
marker.setTitle(address);
marker.setVisible(true);
markers.push(marker);
address = address + 'W <a class="link" href="#" alt="' + address + '" title="Favourite" data-markerid='" + (markers.length - 1) + "'>F</a>';
$('#trip_location').append(address);
google.maps.event.addListener(marker, 'click', function(e) {
infowindow.setContent('<div><strong>' + marker.title + '</strong><br>');
infowindow.open(map, marker);
});
google.maps.event.trigger(marker, 'click');
}
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(-33.8688, 151.2195),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
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);
google.maps.event.addListener(autocomplete, 'place_changed', function() {
infowindow.close();
input.className = '';
var place = autocomplete.getPlace();
if (!place.geometry) {
// Inform the user that the place was not found and return.
input.className = 'notfound';
return;
}
var location = place.geometry.location;
var address = place.formatted_address;
createMarker(place);
});
}
$('#trip_location').on('click', '.link', function(e) {
e.preventDefault();
var location = $(this).attr('alt');
var markerid = $(this).data('markerid');
var marker = markers[markerid];
});
$('.clear').click(function() {
$('#searchTextField').val('');
});
google.maps.event.addDomListener(window, 'load', initialize);
});

Gmap3 show all the available markers on the map from 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.

How to select prepended element

i have a upload form that uses the new multiple attribute and i made an ajax upload form to make things more user friendly. My problem is im trying to update percentages for all of these files that are being uploaded and appended to a div, instead of one percentage being updated all of them get updated from the last file. Here is some code.
$('#File').change(function(event) {
for(I = 0; I < this.files.length; I++)
{
var Name = this.files[I].name;
var Size = this.files[I].size;
var Type = this.files[I].type;
$('#UploadContent').prepend('<div class="UploadLabel" style="width:60%;">'+Name+'</div><div class="UploadLabel UploadPercent" style="width:10%;">0%</div><div class="UploadLabel" style="width:15%;">N/A</div><div class="UploadLabel" style="width:15%;">'+Type+'</div>');
var Data = new FormData();
Data.append('File[]', this.files[I]);
var Request = new XMLHttpRequest();
Request.upload.addEventListener('progress', function(event){
if(event.lengthComputable)
{
var Percent = event.loaded / event.total;
var Progress = $('#UploadContent').find('.UploadPercent');
$(Progress).text(Math.round(Percent * 100) + '%');
}
});
Request.upload.addEventListener('load', function(event) {
});
Request.open('POST', '/Home/Upload/Upload.php');
Request.setRequestHeader('Chache-Control', 'no-cache');
Request.send(Data);
$('#UploadModal').fadeIn('fast');
}
});
now as you can see in the progress listener my
var progress = $('#UploadContent').find('.UploadPercent');
how would i select the file that is supposed to be updated correctly. If someone can find a comepletely different method to change the percent that would be great too! - Thanks!
When you're prepending, add a new, specific class (yes, you could use an id, but I'd just stick to class) to the .UploadPercent element:
$('#UploadContent').prepend('<div class="UploadLabel" style="width:60%;">'+Name+'</div><div class="UploadLabel UploadPercent UploadTarget' + I + '" style="width:10%;">0%</div><div class="UploadLabel" style="width:15%;">N/A</div><div class="UploadLabel" style="width:15%;">'+Type+'</div>');
// LOOK HERE----------------------------------------------------------------------------------------------------------------------^ HERE
And when you're targeting, use this:
var progress = $('#UploadContent').find('.UploadTarget' + I);
Because you need the value of I to be accurate based on where you are in the loop, you need to use a closure as well. So your code will end up looking like:
$('#File').change(function(event) {
for(I = 0; I < this.files.length; I++) {
(function (I) {
// Your current code inside the for loop
})(I);
}
});
While the example from above is definitely an option, it probably makes more sent to just store a reference to the newly inserted element and not have to deal with a new class and I, and then use it later.
Here is the final code I'd use:
http://jsfiddle.net/MeL7L/2/
$("#File").on("change", function (event) {
for (var i = 0; i < this.files.length; i++) {
(function (curFile, i) {
var Name = curFile.files[i].name;
var Size = curFile.files[i].size;
var Type = curFile.files[i].type;
var newEl = "";
newEl += '<div class="UploadLabel" style="width:60%;">' + Name + '</div>';
newEl += '<div class="UploadLabel UploadPercent" style="width:10%;">0%</div>';
newEl += '<div class="UploadLabel" style="width:15%;">N/A</div>';
newEl += '<div class="UploadLabel" style="width:15%;">' + Type + '</div>';
newEl = $(newEl);
$("#UploadContent").prepend(newEl);
var Data = new FormData();
Data.append("File[]", curFile.files[i]);
var Request = new XMLHttpRequest();
Request.upload.addEventListener("progress", function (event){
if (event.lengthComputable) {
var Percent = event.loaded / event.total;
var Progress = newEl.find(".UploadPercent");
Progress.text(Math.round(Percent * 100) + "%");
}
});
Request.upload.addEventListener("load", function(event) {});
Request.open("POST", "/Home/Upload/Upload.php");
Request.setRequestHeader("Cache-Control", "no-cache");
Request.send(Data);
$("#UploadModal").fadeIn("fast");
})(this, i);
}
});

How to render a route on google map with lat long from previous page by html form?

I want to render route on google map by lat long from previous page(send by html form)
and put the recieve value on php hidden type then pull value by jquery and define a start,end point
from value in hidden type finally call routefunction but it's not show the way route
I try to put alert in render section it's work fine but not show way route.I don't know why
This is my code
<?php
//get lat long from previous page html form
$press = $_POST["send"];
$lat1 = $_POST["lat1"];
$long1 = $_POST["long1"];
$lat2 = $_POST["lat2"];
$long2 = $_POST["long2"];
?>
<!DOCTYPE html>
<head>
<script type="text/javascript" src="./jquery.min.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=my_key&sensor=false"></script>
<script type="text/javascript">
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var rendererOptions = {draggable: true}; //define dragble direction
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
var center = new google.maps.LatLng(13.76493,100.5383);
var mapOptions = {
zoom:7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: center
}
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions); //render map
calcRoute(); //call route function
}
function calcRoute()
{//get lat long from hidden type
$(document).ready(function(){
var lat1 = $("#lat1").val();
var long1 = $("#long1").val();
var lat2 = $("#lat2").val();
var long2 = $("#long2").val();
var start = new google.maps.LatLng(lat1,long1);//define start point
var end = new google.maps.LatLng(lat2,long2);//define end point
var request = {
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
alert("DO"); //it's show alert when redirect from previous page
}
});
});
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:500px; height:400px"></div>
<?php
//put value from previous page on hidden type
echo "<input type='hidden' id='lat1' value='$lat1'>";
echo "<input type='hidden' id='long1' value='$long1'>";
echo "<input type='hidden' id='lat2' value='$lat2'>";
echo "<input type='hidden' id='long2' value='$long2'>";
?>

Categories