displaying multiple GoogleMap markers on map - php

I'm trying to display an array of postcodes onto a google map using PHP and using the Symfony Framework (1.0)
The main problem I am having, is that there is some text associated with each marker, i.e when you click the marker a popup appears.
The main problem is that the text should point to the correct postcode/marker on the map, but for some reason this doesn't seem to be the case:
<?php
$addresses = array();
foreach($contents->getResults() as $content):
$addresses[] = array(
'postcode'=>sprintf('%s',str_replace(' ','',$content->getPostalCode())),
'html'=>escape_javascript(get_partial('property/propertyList',array('content'=>$content))),
);
endforeach;
?>
<?php
echo javascript_tag("
var map;
var localSearch = new GlocalSearch();
var center = false;
var icon = new GIcon();
icon.image = 'http://www.google.com/mapfiles/marker.png';
icon.shadow = 'http://www.google.com/mapfiles/shadow50.png';
icon.iconSize = new GSize(20, 34);
icon.shadowSize = new GSize(37, 34);
icon.iconAnchor = new GPoint(10, 34);
var delay = 100;
var bounds = new GLatLngBounds();
var addresses = ".json_encode($addresses).";
var nextAddress = 0;
function theNext() {
if (nextAddress < addresses.length) {
var postcode = addresses[nextAddress].postcode;;
var html = addresses[nextAddress].html
setTimeout('getAddress(\"'+postcode+'\",\"'+html+'\",theNext)', delay);
nextAddress++;
}
}
function getAddress(search, html, next) {
usePointFromPostcode(search, html);
next();
}
var geoCount = 0;
function usePointFromPostcode(address, html, callbackFunction) {
localSearch.setSearchCompleteCallback(null,
function() {
if (localSearch.results[0])
{
geoCount++;
var resultLat = localSearch.results[0].lat;
var resultLng = localSearch.results[0].lng;
var point = new GLatLng(resultLat,resultLng);
var marker = new GMarker(point);
GEvent.addListener(marker, 'click', function() {
marker.openInfoWindowHtml(html);
});
map.addOverlay(marker);
bounds.extend(point);
if(geoCount == addresses.length) {
setCenterToBounds();
}
}else{
//console.info('Postcode not found!', address);
}
});
localSearch.execute(address + ', UK');
}
function placeMarkerAtPoint(point, html)
{
var marker = new GMarker(point,icon);
map.addOverlay(marker);
}
function setCenterToBounds()
{
map.setCenter(bounds.getCenter());
map.setZoom(map.getBoundsZoomLevel(bounds));
console.info('zoom',map.getBoundsZoomLevel(bounds));
}
function mapLoad() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById('map'));
map.addControl(new GLargeMapControl());
map.addControl(new GMapTypeControl());
theNext();
}
}
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
oldonload();
func();
}
}
}
function addUnLoadEvent(func) {
var oldonunload = window.onunload;
if (typeof window.onunload != 'function') {
window.onunload = func;
} else {
window.onunload = function() {
oldonunload();
func();
}
}
}
addLoadEvent(mapLoad);
addUnLoadEvent(GUnload);
")
?>
It only happens on some of the markers though. It is like it finds the postcode, puts the marker on, but then displays the wrong details for it

Ok, so it seems that the data coming back from Google, seemed to come back in the wrong order.
Changing the var delay = 100 to var delay = 200 seemed to fix this
Even though it made the map load a little bit slower

Related

Google map API Shows Blank Screen in my Laravel Application

In my Laravel Application i use google map to Display Route and Distance Between Two Places. after setting google map, i test my app. its display as Blank Screen. I even registered the application using a key that I applied for on Google's website. I have been working on this for 2 hours and cannot figure it out.
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=MY API KEY&libraries=places&callback=initMap&sensor=false" async defer></script>
<script type="text/javascript">
function GetRoute() {
source = document.getElementById("pickupaddress").value;
destination = document.getElementById("deliveryaddress").value;
var request = {
origin: source,
destination: destination,
travelMode: google.maps.TravelMode.DRIVING
};
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: [source],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function (response, status) {
if (status == google.maps.DistanceMatrixStatus.OK && response.rows[0].elements[0].status != "ZERO_RESULTS") {
var distance = response.rows[0].elements[0].distance.text;
var dvDistance = document.getElementById("distanceops");
dvDistance.innerHTML = "";
dvDistance.innerHTML += distance;
} else {
alert("Unable to find the distance via road.");
}
});
}
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
mapTypeControl: false,
center: {lat: 4.2105, lng: 101.9758},
zoom: 8
});
new AutocompleteDirectionsHandler(map);
}
/**
* #constructor
*/
function AutocompleteDirectionsHandler(map) {
this.map = map;
this.originPlaceId = null;
this.destinationPlaceId = null;
this.travelMode = 'WALKING';
var originInput = document.getElementById('pickupaddress');
var destinationInput = document.getElementById('deliveryaddress');
this.directionsService = new google.maps.DirectionsService;
this.directionsDisplay = new google.maps.DirectionsRenderer;
this.directionsDisplay.setMap(map);
var deliveryrestrictOptions = {componentRestrictions: {country: 'my'},placeIdOnly: true};
var originAutocomplete = new google.maps.places.Autocomplete(
originInput, deliveryrestrictOptions);
var destinationAutocomplete = new google.maps.places.Autocomplete(
destinationInput,deliveryrestrictOptions);
this.setupPlaceChangedListener(originAutocomplete, 'ORIG');
this.setupPlaceChangedListener(destinationAutocomplete, 'DEST');
}
// Sets a listener on a radio button to change the filter type on Places
// Autocomplete.
AutocompleteDirectionsHandler.prototype.setupClickListener = function(id, mode) {
var radioButton = document.getElementById(id);
var me = this;
radioButton.addEventListener('click', function() {
me.travelMode = mode;
me.route();
});
};
AutocompleteDirectionsHandler.prototype.setupPlaceChangedListener = function(autocomplete, mode) {
var me = this;
autocomplete.bindTo('bounds', this.map);
autocomplete.addListener('place_changed', function() {
var place = autocomplete.getPlace();
if (!place.place_id) {
window.alert("Please select an option from the dropdown list.");
return;
}
if (mode === 'ORIG') {
me.originPlaceId = place.place_id;
} else {
me.destinationPlaceId = place.place_id;
}
me.route();
});
};
AutocompleteDirectionsHandler.prototype.route = function() {
if (!this.originPlaceId || !this.destinationPlaceId) {
return;
}
var me = this;
this.directionsService.route({
origin: {'placeId': this.originPlaceId},
destination: {'placeId': this.destinationPlaceId},
travelMode: this.travelMode
}, function(response, status) {
if (status === 'OK') {
me.directionsDisplay.setDirections(response);
GetRoute();
} else {
window.alert('Directions request failed due to ' + status);
}
});
};
window.ParsleyConfig = {
errorsWrapper: '<div></div>',
errorTemplate: '<span class="error-text"></span>',
classHandler: function (el) {
return el.$element.closest('input');
},
successClass: 'valid',
errorClass: 'invalid'
};
</script>
I have worked on google maps. Google maps won't load inside a modal or any hidden divs (for perf reasons).
Here is what you do. Trigger resize on the map and it should render the map.
google.maps.event.trigger(map, 'resize') where map is your map instance name.

PHP PASS VARIABLE (..AJAX\NEGOZI.PHP)

I must adjust a website, but I don't understand this function:
var geocoder;
var map;
var markersArray = [];
var bounds;
var infowindow;
var appena_entrato = true;
var mappa_attiva = "tt";
-- Initialize_map
function initialize_map() {
markersArray = [];
var myLatlng = new google.maps.LatLng(45.6841895,11.4775636);
var myOptions = {
zoom: 14,
maxZoom: 18,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false,
disableDoubleClickZoom: true,
mapTypeControl: false,
panControl: true,
panControlOptions: {
position: google.maps.ControlPosition.TOP_RIGHT
},
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE,
position: google.maps.ControlPosition.RIGHT_TOP
},
scaleControl: false,
streetViewControl: false
}
geocoder = new google.maps.Geocoder();
map = new google.maps.Map(document.getElementById("map-canvas-"+mappa_attiva), myOptions);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(45.6841895,11.4775636),
map: map,
title:"COMPANY NAME"
});
marker.setMap(map);
var contentString = '<div>'+
'<h2>COMPANY NAME</h2>'+
'<div style="width:400px;">'+
'<p>ADDRESS<br>' +
'Ph. +39 0000- Fax. +39 00000</p>'+
'</div>'+
'</div>';
marker.infowindow = new google.maps.InfoWindow({
content: contentString
});
google.maps.event.addListener(marker, 'click', function() {
marker.infowindow.open(map,marker);
});
markersArray.push(marker);
for (i in markersArray) {
markersArray[i].infowindow.open(map,markersArray[i]);
}
getLocation();
}
-- GetLocation
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
//console.log("Geolocation not supported!");
}
}
-- ShowPosition
function showPosition(position) {
var myLatlng = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
map.setCenter(myLatlng);
map.setZoom(9);
coordsAddress(position.coords.latitude,position.coords.longitude,function(results){
for (var i=0; i<results.length; i++) {
for (var b=0; b<results[i].types.length; b++) {
if (results[i].types[b] == "administrative_area_level_2") {
var indice = i;
}
}
}
for (var i=0; i<results[indice].address_components.length; i++) {
for (var b=0; b<results[indice].address_components[i].types.length; b++) {
if (results[indice].address_components[i].types[b] == "administrative_area_level_2") {
var postalCode = results[indice].address_components[i].short_name;
}
}
}
$("#provincia option:selected").removeAttr("selected");
$("#provincia option[value="+postalCode+"]").prop("selected",true);
mostra_coords(position.coords.latitude, position.coords.longitude, 50);
});
}
-- Code Address
function codeAddress(zipCode,country,callback) {
geocoder.geocode({address: zipCode, region: country}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
callback(results);
} else {
alert('No results found');
}
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
-- CoordsAddress
function coordsAddress(latitude,longitude,callback) {
var myLatlng = new google.maps.LatLng(latitude,longitude);
geocoder.geocode({'latLng': myLatlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
callback(results);
} else {
alert('No results found');
}
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
--Add marker
function add_spillo(indirizzo) {
var id = indirizzo.attr("id");
var geo = indirizzo.attr("rel");
var text = indirizzo.parent().html();
var icona = 'img/point.png';
indirizzo = geo.split(",");
var myLatlng = new google.maps.LatLng(indirizzo[0],indirizzo[1]);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
icon: icona
});
marker.infowindow = new google.maps.InfoWindow({
content: text
});
google.maps.event.addListener(marker, 'click', function () {
marker.infowindow.open(map, marker);
});
markersArray.push(marker);
bounds.extend(myLatlng);
}
-- Map centre
function centra_mappa(coords) {
var lat = coords.lat();
var lon = coords.lng();
var max_lon = map.getBounds().getNorthEast().lng();
var max_lat = map.getBounds().getNorthEast().lat();
var min_lon = map.getBounds().getSouthWest().lng();
var min_lat = map.getBounds().getSouthWest().lat();
max_lon = Math.max(lon, max_lon);
min_lon = Math.min(lon, min_lon);
max_lat = Math.max(lat, max_lat);
min_lat = Math.min(lat, min_lat);
var ne = new google.maps.LatLng(max_lat, max_lon);
var sw = new google.maps.LatLng(min_lat, min_lon);
var nuovi_bordi = new google.maps.LatLngBounds(sw, ne);
map.fitBounds(nuovi_bordi);
}
-- Delete Overlays
function deleteOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].infowindow.close();
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
}
-- Coords Show
function mostra_coords(lat, lng, distance) {
customurl = "../ajax/negozi.php";
$("#boxNegozi-"+mappa_attiva+" ul").load(customurl, {
lat: lat,
lng: lng,
distance: distance,
brand: mappa_attiva
}, function(data) {
if (data == "") return alert("No shops found on your search1");
deleteOverlays();
bounds = new google.maps.LatLngBounds();
$(data).find("input").each(function(index, element) {
add_spillo($(this));
});
map.fitBounds(bounds);
appena_entrato = false;
});
}
-- Provincia Show
function mostra(provincia) {
customurl = "../ajax/negozi.php";
$("#boxNegozi-"+mappa_attiva+" ul").load(customurl, {
provincia: provincia,
brand: mappa_attiva
}, function(data) {
if (data == "") return alert("No shops found on your search2");
deleteOverlays();
bounds = new google.maps.LatLngBounds();
$(data).find("input").each(function(index, element) {
add_spillo($(this));
});
map.fitBounds(bounds);
});
}
--Nazione Show
function mostra_nazione(nazione) {
customurl = "../ajax/negozi.php";
$("#boxNegozi-"+mappa_attiva+" ul").load(customurl, {
country: nazione,
brand: mappa_attiva
}, function(data) {
if (data == "") return alert("No shops found on your search3");
deleteOverlays();
bounds = new google.maps.LatLngBounds();
$(data).find("input").each(function(index, element) {
add_spillo($(this));
});
map.fitBounds(bounds);
});
}
google.maps.event.addDomListener(window, 'load', initialize_map);
$(document).ready(function(){
$("#provincia-ttt").change(function(){
var provincia = $(this).val();
mostra(provincia);
});
$("#provincia-tt").change(function(){
var provincia = $(this).val();
mostra(provincia);
});
$("#nazione-ttt").change(function(){
console.log($(this).val());
if ($(this).val() == "IT") $("#teen_provincia").show();
else {
$("#teen_provincia").hide();
mostra_nazione($(this).val());
}
});
$('#tabs a').click(function (e) {
e.preventDefault();
$(this).tab('show');
if ($(this).attr('href') == "#orange") {
mappa_attiva = "ttt";
} else {
mappa_attiva = "tt";
}
initialize_map();
$("#provincia-"+mappa_attiva).val("");
$("#boxNegozi-"+mappa_attiva+" ul").html("");
});
});
-- I MADE THIS PHP PAGE BUT DON'T WORK, WHERE I MAKE ERROR? thanks in advance
<?
$dbname ='ltaketwd_db'; //Name of the database
$dbuser ='ltaketwd_admin'; //Username for the db
$dbpass ='Twork.01'; //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 negozi");
while ($row = mysql_fetch_array($query)){
$lat=$row['lat'];
$lng=$row['lng'];
$distance=$row['distance'];
$name=$row['name'];
$indirizzo=$row['indirizzo'];
$provincia=$row['provincia'];
$nazione=$row['nazione'];
}
?>
AJAX = Asynchronous JavaScript and XML.
In short; AJAX allows you to load data in the background, manipulate it and display it on the webpage, without needing a page reload.
Have a look at jQuery's documentation for load().
You'll see that load() takes up to three parameters, which is what happens here :
$("#boxStore-"+active_map+" ul") // the element you want as container for your document
.load(
customurl, // 1) the page/document you want to load in the container
{lat:lat, ..... }, // 2) variables you pass to the page so it generates differently
function(data) {
/* 3) callback function, that will be executed after load() is finished. "data" is the page/document you called. */
}
);

Marker on Point in polygon not displaying

I want to display marker inside the polygon like this example that i followed.
Point in polygon
But the marker did not show up.I think there is missing in my code,this is the coordinates that i saved to my database.
53.198524,-105.762383
53.198566,-105.765083
53.199001,-105.762314
53.199394,-105.765083
53.199409,-105.765091
53.199421,-105.762123
53.199425,-105.763580
I appreciate someone can help me to figure it out on how to get this work.
var map;
var polySides = 7;
var polyLat = new Array();
polyLat[0]=53.198524;
polyLat[1]=53.198566;
polyLat[2]=53.199001;
polyLat[3]=53.199394;
polyLat[4]=53.199409;
polyLat[5]=53.199421;
polyLat[6]=53.199425;
polyLat[7]=53.198524;
var polyLng = new Array();
polyLng[0]=-105.762383;
polyLng[1]=-105.765083;
polyLng[2]=-105.762314;
polyLng[3]=-105.765083;
polyLng[4]=-105.765091;
polyLng[5]=-105.762123;
polyLng[6]=-105.763580;
polyLng[7]=-105.762383;
var maxLat = Math.max.apply(null,polyLat);
var minLat = Math.min.apply(null,polyLat);
var maxLng = Math.max.apply(null,polyLng);
var minLng = Math.min.apply(null,polyLng);
var bounds = new google.maps.LatLngBounds;
function initialize() {
initial = new google.maps.LatLng(53.199246241276875,-105.76864242553711);
var mapOptions = {
zoom: 16,
center: initial,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE
},
mapTypeControl: false
};
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
}
$(function () {
$.ajax({
type:'post',
dataType:'json',
data:'maxLat='+maxLat +'&minLat='+minLat +'&maxLng='+maxLng +'&minLng='+minLng,
url:'polygeofence.php',
success: function(data){
bounds = new google.maps.LatLngBounds();
$.each(data,function(i,dat){
if (pointInPolygon(polySides,polyLat,polyLng,dat.lat,dat.lng)){
var latlng = new google.maps.LatLng(parseFloat(dat.lat),parseFloat(dat.lng));
addMarker(latlng);
bounds.extend(latlng);
}
});
map.fitBounds(bounds);
}
});
});
function pointInPolygon(polySides,polyX,polyY,x,y) {
var j = polySides-1 ;
oddNodes = 0;
for (i=0; i<polySides; i++) {
if (polyY[i]<y && polyY[j]>=y || polyY[j]<y && polyY[i]>=y) {
if (polyX[i]+(y-polyY[i])/(polyY[j]-polyY[i])*(polyX[j]-polyX[i])<x) {
oddNodes=!oddNodes;
}
}
j=i;
}
return oddNodes;
}
function addMarker(latlng){
marker = new google.maps.Marker({
position: latlng,
map: map,
draggable: false
});
marker.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
php code
$minlat = $_POST['minLat'];
$maxlat = $_POST['maxLat'];
$minlng = $_POST['minLng'];
$maxlng = $_POST['maxLng'];
$queryresult = mysql_query("SELECT * FROM geofencetbl WHERE
(lat>='$minlat' AND lat<='$maxlat')
AND (lng>='$minlng' AND lng<='$maxlng')
");
$results = array(
'lat' => array(),
'lng' => array(),
);
while($row=mysql_fetch_array($queryresult,MYSQL_BOTH)){
$results['lat'][] =$row['lat'];
$results['lng'][] =$row['lng'];
}
echo json_encode($results);
Edit:after edited my code,I have problem on my sucess dat.lat and dat.lng are undefined
Quite a lot of issues in your code. You are missing many variables declarations, and other stuff.
I commented most of my changes like that:
// missing bounds object here
var bounds = new google.maps.LatLngBounds();
I removed the AJAX part since of course it is not going to work. I am just creating one marker. No polygon. But at least this shows you that a correct LatLng object is passed to the addMarker() function.
Hope this helps!
JSFiddle demo
Edit:
Here is how you should create your JSON output.
$sql = "SELECT * FROM geofencetbl WHERE (lat>='$minlat' AND lat<='$maxlat') AND (lng>='$minlng' AND lng<='$maxlng')";
$result = $db->query($sql) or die($db->error);
while ($obj = $result->fetch_object()) {
$results[] = $obj;
}
echo json_encode($results);
Then in your AJAX success function, log dat and you should understand how to deal with it!

Google maps doesn't show (on click button)

I am having problems generating a Google map and showing it on my page.
This is my view. What can I do to make this work properly?
<?php
$telephones = $this->telephones;
$telephonesa = array();
foreach($telephones as $telephone){
array_push($telephonesa, $telephone);
}
?>
<div id="googleMap" style="width:500px;height:380px;"></div>
// client-side
<script>
var object = {};
object.dist = 100000;
$(document).ready(function() {
$( "#getclosest" ).click(function() {
$.mobile.loading( 'show' );
getLocation();
});
});
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
else{
alert("Geolocation is not supported by this browser.");
}
}
function showPosition(position)
{
var currlat = position.coords.latitude;
var currlon = position.coords.longitude;
getClosest(currlat, currlon);
}
function getClosest(currlat, currlon){
var telephones = <?php echo json_encode($telephonesa); ?>;
var length = telephones.length,
element = null;
for (var i = 0; i < length; i++) {
element = telephones[i];
object.distance = getDistanceBetweenLatLongs(currlat, currlon, element.Location.Longitude, element.Location.Latitude);
if (object.distance < object.dist){
object.dist = object.distance;
object.index = i;
}
}
showToilet(object.index);
}
function showToilet(index){
var telephones = <?php echo json_encode($telephonesa); ?>;
var telephone = telephones[index];
showGooglemaps(telephone.Location.Latitude, telephone.Location.Longitude);
}
function showGooglemaps(lat,lon){
google.maps.visualRefresh = true;
var myCenter=new google.maps.LatLng(lat,lon);
var marker;
function initialize()
{
var mapProp = {
center:myCenter,
zoom:13,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("googleMap")
,mapProp);
marker=new google.maps.Marker({
position:myCenter,
animation:google.maps.Animation.BOUNCE
});
marker.setMap(map);
google.maps.event.trigger(map, 'load');
}
$("#getclosest").hide();
$.mobile.loading( 'hide' );
google.maps.event.addDomListener(window, 'load', initialize);
}
As you can see I have a function 'ShowGooglemaps' that I call but the output shows nothing ...
The load-event of window fires when all ressources have been loaded, but the function ShowGooglemaps will be called when you click on the button. At this time usually the load-event already has been fired(and will not fire again, and the callback also will not be executed immediately as it e.g. jQuery's ready-listener does) .
This line:
google.maps.event.addDomListener(window, 'load', initialize);
..is useless, initialize will never be called.
There is no need to wrap the code that initializes the map into the initialize-function, simply execute the code without waiting for the load-event.

Can't load waypoints and routes on Google Maps api v3

I want to display multiple directions with dragable waypoints and save each waypoints.
On my project I can click on the map to create the routes, generating a wayA point and a wayB point and draw a route between them. So, I can make multiple routes.
I can also save them on the database.
The problem is load this points on the map again fetching them on the database and drawing all on the map.
I have two pages, on index.htm you can draw your routes and save them, and on loady.htm you can load them on the map.
I tried somethings but without sucess, I will post my try here.
This is my resumed index.htm
var map, ren, ser;
var data = {};
var wayA = [];
var wayB = [];
var directionResult = [];
function goma() <---Initialize
{
google.maps.event.addListener(map, "click", function(event) {
if (wayA.length == wayB.length) {
wayA.push(new google.maps.Marker({
draggable: true,
position: event.latLng,
map: map
}));
} else {
wayB.push(new google.maps.Marker({
draggable: true,
position: event.latLng,
map: map
}));
ren = new google.maps.DirectionsRenderer( {'draggable':true} );
ren.setMap(map);
ren.setPanel(document.getElementById("directionsPanel"));
ser = new google.maps.DirectionsService();
ser.route({ 'origin': wayA[wayA.length-1].getPosition(), 'destination': wayB[wayB.length-1].getPosition(), 'travelMode': google.maps.DirectionsTravelMode.DRIVING},function(res,sts) {
if(sts=='OK') {
directionResult.push(res);
ren.setDirections(res);
} else {
directionResult.push(null);
} })
} }); }
function save_waypoints()
{
var w=[],wp;
var rleg = ren.directions.routes[0].legs[0];
data.start = {'lat': rleg.start_location.lat(), 'lng':rleg.start_location.lng()}
data.end = {'lat': rleg.end_location.lat(), 'lng':rleg.end_location.lng()}
var wp = rleg.via_waypoints
for(var i=0;i<wp.length;i++)w[i] = [wp[i].lat(),wp[i].lng()]
data.waypoints = w;
var str = JSON.stringify(data)
var jax = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
jax.open('POST','process.php');
jax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
jax.send('command=save&inventoresdegara='+str)
jax.onreadystatechange = function(){ if(jax.readyState==4) {
if(jax.responseText.indexOf('bien')+1)alert('Mapa Atualizado !');
else alert(jax.responseText)
}}
}
This is the resumed loady.htm with my try
var map, ren, ser;
var data = {};
var wayA = [];
var wayB = [];
var directionResult = [];
function goma() {
ren = new google.maps.DirectionsRenderer( {'draggable':true} );
ren.setMap(map);
ren.setPanel(document.getElementById("directionsPanel"));
ser = new google.maps.DirectionsService();
fetchdata();
function setroute(os)
{
var wp = [];
for(var i=0;i<os.waypoints.length;i++)
wp[i] = {'location': new google.maps.LatLng(os.waypoints[i][0], os.waypoints[i][3]),'stopover':false }
ser.route({ 'origin': wayA[wayA.length-1].setPosition(), 'destination': wayB[wayB.length-1].setPosition(), 'travelMode': google.maps.DirectionsTravelMode.DRIVING},function(res,sts) {
if(sts=='OK') {
directionResult.push(res);
ren.setDirections(res);
} else {
directionResult.push(null);
}
});
}
function fetchdata()
{
var jax = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
jax.open('POST','process.php');
jax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
jax.send('command=fetch')
jax.onreadystatechange = function(){ if(jax.readyState==4) {
try { setroute( eval('(' + jax.responseText + ')') ); }
catch(e){ alert(e); }
}}
}
This is my php file:
<?
if($_REQUEST['command']=='save')
{
$query = "insert into inventoresdegara set value='$data'";
if(mysql_query($query))die('bien');
die(mysql_error());
}
if($_REQUEST['command']=='fetch')
{
//$query = "select value from inventoresdegara";
$query = "SELECT value FROM inventoresdegara";
if(!($res = mysql_query($query)));
$rs = mysql_fetch_array($res,1);
die($rs['value']);
}
?>
This is a image from my database to you know how the information are saved
The only thing that I need to do is load this values to the map, please help me =).
Thanks !
After my try, the loady.htm was this on ser.routes
ser.route({'origin':new google.maps.LatLng(os.start.lat,os.start.lng),
'destination':new google.maps.LatLng(os.end.lat,os.end.lng),
'waypoints': wp,
'travelMode': google.maps.DirectionsTravelMode.DRIVING},function(res,sts) {
if(sts=='OK')ren.setDirections(res);
}
If the reason to saving waypoints is to reproduce the route they came from, you're better off saving the entire route and then showing it on the map without re-requesting the route again. See Displaying results of google direction web service without using javascript api
Otherwise, if you just want to get a fresh route from A to B through waypoints, your current approach of calling ser.route() with them is correct.

Categories