currently i am create a small that display markers on google map. Coordinates come from mysql database but i getting the error i don't know why it's came.
ERRor - XMLHttpRequest cannot load http://localhost:8080/markers.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.1.7:8100' is therefore not allowed access. The response had HTTP status code 404.
markers.php
<?php
//Create a connection to the database
$mysqli = new mysqli("localhost", "test");
if (!$mysqli) {
die("Connection failed: " . mysqli_connect_error());
}
//The default result to be output to the browser
$result = "{'success':false}";
//Select everything from the table containing the marker informaton
$query = "SELECT * FROM marker";
//Run the query
$dbresult = $mysqli->query($query);
//Build an array of markers from the result set
$markers = array();
while($row = $dbresult->fetch_array(MYSQLI_ASSOC)){
$markers[] = array(
'id' => $row['id'],
'name' => $row['name'],
'lat' => $row['lat'],
'lng' => $row['lng']
);
}
//If the query was executed successfully, create a JSON string containing the marker information
if($dbresult){
$result = "{'success':true, 'markers':" . json_encode($markers) . "}";
}
else
{
$result = "{'success':false}";
}
//Set these headers to avoid any issues with cross origin resource sharing issues
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type,x-prototype-version,x-requested-with');
//Output the result to the browser so that our Ionic application can see the data
echo($result);
?>
app.js
angular.module('starter', ['ionic', 'ngCordova'])
.run(function($ionicPlatform, GoogleMaps) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if(window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if(window.StatusBar) {
StatusBar.styleDefault();
}
GoogleMaps.init();
})
})
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('map', {
url: '/',
templateUrl: 'templates/map.html',
controller: 'MapCtrl'
});
$urlRouterProvider.otherwise("/");
})
.factory('Markers', function($http) {
var markers = [];
return {
getMarkers: function(){
return $http.get("http://localhost:8080/markers.php").then(function(response){
markers = response;
return markers;
});
}
}
})
.factory('GoogleMaps', function($cordovaGeolocation, Markers){
var apiKey = false;
var map = null;
function initMap(){
var options = {timeout: 10000, enableHighAccuracy: true};
$cordovaGeolocation.getCurrentPosition(options).then(function(position){
var latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var mapOptions = {
center: latLng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), mapOptions);
//Wait until the map is loaded
google.maps.event.addListenerOnce(map, 'idle', function(){
//Load the markers
loadMarkers();
});
}, function(error){
console.log("Could not get location");
//Load the markers
loadMarkers();
});
}
function loadMarkers(){
//Get all of the markers from our Markers factory
Markers.getMarkers().then(function(markers){
console.log("Markers: ", markers);
var records = markers.data.markers;
for (var i = 0; i < records.length; i++) {
var record = records[i];
var markerPos = new google.maps.LatLng(record.lat, record.lng);
// Add the markerto the map
var marker = new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP,
position: markerPos
});
var infoWindowContent = "<h4>" + record.name + "</h4>";
addInfoWindow(marker, infoWindowContent, record);
}
});
}
function addInfoWindow(marker, message, record) {
var infoWindow = new google.maps.InfoWindow({
content: message
});
google.maps.event.addListener(marker, 'click', function () {
infoWindow.open(map, marker);
});
}
return {
init: function(){
initMap();
}
}
})
.controller('MapCtrl', function($scope, $state, $cordovaGeolocation) {
});
There is a configuration to do with Ionic :
http://ionicframework.com/docs/cli/test.html
Or if you are using google chrome you can add this plugin, it solve the problem for me :
https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi
Hope it should help you
Related
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.
I am new to Openlayers3.....I am trying to load data from database using ajax & php to load vector data to openlayers3,I am stuck and don't know what is the problem.
here is my code
Can anyone help me in that?
$(document).ready(function()
{
//extent of the map
view = new ol.View({
center:ol.proj.transform([125.7799,8.7965], 'EPSG:4326', 'EPSG:3857'),
zoom:11,
maxZoom:18,
minZoom:2
});
//BaseLayer
var baseLayer = new ol.layer.Tile({
source: new ol.source.OSM()
});
// create a vector source that loads a GeoJSON file
var vectorSource = new ol.source.Vector({
projection: 'EPSG:4326',
url: 'data/Boundaries.geojson',
format: new ol.format.GeoJSON()
});
var geoJSONFormat = new ol.format.GeoJSON();
var farmersSource = new ol.source.Vector({
loader: function(extent, resolution, projection) {
var url = 'allfarmers_geojson.php?p=' + extent.join(',');
$.ajax({
url: url,
success: function(data) {
var features = geoJSONFormat.readFeatures(data);
farmersSource.addFeatures(features);
}
});
},
strategy: ol.loadingstrategy.bbox
});
// Polygons
var createPolygonStyleFunction = function() {
return function(feature, resolution) {
var style = new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'blue',
width: 1
}),
fill: new ol.style.Fill({
color: '#faeaac'
}),
//text: createTextStyle(feature)
});
return [style];
};
};
// a vector layer to render the source
var vectorLayer = new ol.layer.Vector({
source: vectorSource,
style:createPolygonStyleFunction()
});
var farmersLayer = new ol.layer.Vector({
source: farmersSource
//style:createPolygonStyleFunction()
});
//Map
var map = new ol.Map({
target:'map',
controls:ol.control.defaults().extend([
new ol.control.ScaleLine(),
new ol.control.ZoomSlider()
]),
renderer: 'canvas',
layers:[baseLayer,vectorLayer,farmersLayer],
view:view
});
//////////styling features and with mouse over color change/////////////
var highlightStyleCache = {};
var featureOverlay = new ol.layer.Vector({
source: new ol.source.Vector(),
map: map,
style: function(feature, resolution) {
var text = resolution < 5000 ? feature.get('NAME_3') : '';
if (!highlightStyleCache[text]) {
highlightStyleCache[text] = new ol.style.Style({
stroke: new ol.style.Stroke({
color: '#f00',
width: 1
}),
fill: new ol.style.Fill({
color: 'rgba(255,0,0,0.1)'
}),
text: new ol.style.Text({
font: '12px Calibri,sans-serif',
text: text,
fill: new ol.style.Fill({
color: '#f00'
})
})
});
}
return highlightStyleCache[text];
}
});
var highlight;
var displayFeatureInfo = function(pixel) {
var feature = map.forEachFeatureAtPixel(pixel, function(feature) {
return feature;
});
if (feature !== highlight) {
if (highlight) {
featureOverlay.getSource().removeFeature(highlight);
}
if (feature) {
featureOverlay.getSource().addFeature(feature);
}
highlight = feature;
}
};
map.on('pointermove', function(evt) {
if (evt.dragging) {
return;
}
var pixel = map.getEventPixel(evt.originalEvent);
displayFeatureInfo(pixel);
});
map.on('click', function(evt) {
displayFeatureInfo(evt.pixel);
});
//////////End of styling features and with mouse over color change/////////////
});
and here is my php file
<?php
$conn = new PDO('mysql:host=localhost;dbname=FarmersDB','root','admin');
$sql = 'SELECT *, _coordinates__latitude AS x, _coordinates__longitude AS y FROM farmers';
if (isset($_GET['bbox']) || isset($_POST['bbox'])) {
$bbox = explode(',', $_GET['bbox']);
$sql = $sql . ' WHERE x <= ' . $bbox[2] . ' AND x >= ' . $bbox[0] . ' AND y <= ' . $bbox[3] . ' AND y >= ' . $bbox[1];
}
$rs = $conn->query($sql);
if (!$rs) {
echo 'An SQL error occured.\n';
exit;
}
$geojson = array(
'type' => 'FeatureCollection',
'features' => array()
);
while ($row = $rs->fetch(PDO::FETCH_ASSOC)) {
$properties = $row;
unset($properties['x']);
unset($properties['y']);
$feature = array(
'type' => 'Feature',
'geometry' => array(
'type' => 'Point',
'coordinates' => array(
$row['x'],
$row['y']
)
),
'properties' => $properties
);
array_push($geojson['features'], $feature);
}
header('Content-type: application/json');
echo json_encode($geojson, JSON_NUMERIC_CHECK);
$conn = NULL;
?>
No exactly sure what problem you're having but try this..You probably need to set the right projection and parse the data response from the server..Projection is EPSG:3857 by default:
success: function(data) {
var JSONData;
try {
JSONData = JSON.parse(data);
} catch(err) {
alert(err);
return;
}
var format = new ol.format.GeoJSON();
var features = format.readFeatures(JSONData, {
featureProjection: 'EPSG:3857'
});
farmersSource.addFeatures(features);
farmersSource.changed();
}
});
Also, on var vectorSource change the project to EPSG:3857. Another thing, you need to add the vectorloader property to you source.vector. For example:
var locationSource = new ol.source.Vector({
url: loc_url,
format: new ol.format.GeoJSON({
defaultDataProjection :'EPSG:3857'
}),
loader: vectorLoader,
strategy: ol.loadingstrategy.all
});
The vectorLoader function looks like this and makes your ajax calls to the server. Special note on loader functions - When clear() is called on the source layer, it will trigger the vector loader function again:
var vectorLoader = function(extent, resolution, projection) {
var url = this.getUrl();
utils.refreshGeoJson(this);
}
var utils = {
refreshGeoJson: function(source,url) {
var now = Date.now();
if (typeof url == 'undefined') {
url = source.getUrl();
}
url += '?t=' + now; //Prevents browser caching if retrieving a geoJSON file
console.info('refreshGeoJson url: ' + url);
this.getJson(url).when({
ready: function(response) {
var JSONResponse;
try {
JSONResponse = JSON.parse(response);
} catch(err) {
alert(err + ' - ' + url);
return;
}
var format = new ol.format.GeoJSON();
var features = format.readFeatures(JSONResponse, {
featureProjection: 'EPSG:3857'
});
source.addFeatures(features);
source.changed();
}
});
},
getJson: function(url) {
var xhr = new XMLHttpRequest(),
when = {},
onload = function() {
console.log(url + ' xhr.status: ' + xhr.status);
if (xhr.status === 200) {
console.log('getJson() xhr: ');
console.dir(xhr);
console.log('getJson() xhr.response: ');
console.dir(xhr.response);
when.ready.call(undefined, xhr.response);
}
if (xhr.status === 404) {
console.log('map file not found! url: ' + url);
}
},
onerror = function() {
console.info('Cannot XHR ' + JSON.stringify(url));
};
xhr.open('GET', url, true);
xhr.setRequestHeader('cache-control', 'no-store');
xhr.onload = onload;
xhr.onerror = onerror;
xhr.send(null);
return {
when: function(obj) { when.ready = obj.ready; }
};
}
};
Threw in a lot of extras here because I'm not sure what your problem is with your code. The example above work great for me retrieving geoJSON files from the server that are periodically changed..It should work the same for you if calling a PHP script, just make sure that the script returns geoJSON data according to this spec: http://geojson.org/geojson-spec.html
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>
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!
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.