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.
Related
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. */
}
);
I have a JavaScript ajax page, which fires an ajax request (using setInterval function) every 20 seconds and gets response in JSON format. In the page; using JSON response I'm displaying the markers on Google map (using API v3) and updating them every 20 seconds based on the location received from ajax response. I'm displaying an infoWindow on click event of marker.
I am using PHP as server side scripting, which generates my ajax response by doing some DB calls.
Everything works fine when I open the page. But slowly the page starts responding slow. I mean when I click on the marker or on related text, page takes a significant time to locate the marker, to load the map and to open the infoWindow. And the slowness of page increases as the time passes. If I refresh the page, again everything starts working fine.
The page don't even show a single error at any point of time and I must add that the auto updation of location of markers works fine throughout the life of the page.
I've tried everything which I found on forums. Like, I've moved to json response from an xml(dom) response. I've tried changing the XMLHttpRequest methods, as the GET requests have tendency to auto cache the data. But nothing helped me. I am completely clueless, what is wrong, what I am doing in my code.
Here is my JavaScript code:
<script type="text/javascript">
var map;
var contentString = "";
var infoWindow = new google.maps.InfoWindow({content: contentString});
var url = "genAjaxResponse.php?id=<?php echo $id; ?>";
var marker;
var gmarkers = new Array();
var icon;
var lastClickedMarker;
var stImgId;
var customIcons = {
Moving: {
icon: 'icons/abc.png'
},
Idle: {
icon: 'icons/xyz.png'
},
Parked: {
icon: 'icons/pqr.png'
},
Alert: {
icon: 'icons/wxy.png'
}
};
function load() { // to be called on onload event of body
map = new google.maps.Map(document.getElementById("map"), {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scaleControl: true,
center:new google.maps.LatLng(15.570128,78.957092)
});
calldownloadUrl(url,map,infoWindow);
directionsDisplay = new google.maps.DirectionsRenderer();
}
function calldownloadUrl(url,map,infoWindow) {
downloadUrl(url,displayMarker,map,infoWindow);
}
function displayMarker(data,map,infoWindow) {
function generateTriggerCallback(object, eventType) {
return function() {
google.maps.event.trigger(object, eventType);
};
}
var namearr = Array();
var json = data.responseText;
var vehicles = eval ("(" + json + ")");
var i = 0;
for (var veh in vehicles)
{
var tag = vehicles[veh];
var veh_no = tag["veh_no"];
var is_stale = tag["is_stale"];
var ignition_off = tag["ignition_off"];
var speed = tag["speed"];
var lat = tag["lat"];
var lng = tag["lng"];
var time = tag["time_stamp"];
var address = tag["address"];
var point = new google.maps.LatLng(
parseFloat(lat),
parseFloat(lng));
var type;
var status;
stImgId = i+1;
if(ignition_off == 0 && speed > 3) {
type = "Moving";
status = type + "(" + speed + " Kmph)";
document.getElementById("img"+stImgId).src = "icons/greenalert2.png";
}
else {
if(ignition_off == 1) {
type = "Parked";
status = type;
document.getElementById("img"+stImgId).src = "icons/greyalert2.png";
}
else {
type = "Idle";
status = type;
document.getElementById("img"+stImgId).src = "icons/yellowalert2.png";
}
}
if(is_stale == 1) {
type = "Alert";
status = type;
document.getElementById("img"+stImgId).src = "icons/redalert2.png";
}
infoWindow.close();
var icon = customIcons[type] || {};
if(typeof gmarkers[i] != 'undefined') {
gmarkers[i].setPosition(point);
gmarkers[i].setIcon(icon.icon);
if(gmarkers[i].id == lastClickedMarker) {
if(map.getBounds().contains(gmarkers[i].getPosition()) === false)
map.setCenter(gmarkers[i].getPosition());
}
}
else
{
gmarkers[i] = new google.maps.Marker({
id: i,
position: point,
icon: icon.icon,
title: veh_no,
map: map
});
}
var html = "<span><p><b>"+veh_no +"</b></p> <p>Address: "+address+"<br />Status: "+status+"<br />Time: "+time+"</p></span>";
namearr[i] = "<span><p><b>"+veh_no +"</b></p> <p>Address: "+address+"<br />Status: "+status+"<br />Time: "+time+"</p></span>";
// -- bind click event to texts (vehicle nos) -- //
var textclick = document.getElementById(i);
textclick.onclick = generateTriggerCallback(gmarkers[i],"click");
// -- bind click event to markers -- //
bindinfoWindow(gmarkers[i], map, infoWindow, namearr[i], icon);
i++;
}
}
function bindinfoWindow(marker, map, infoWindow, html, icon) {
google.maps.event.addListener(marker, 'click', function() {
lastClickedMarker = marker.id;
map.setCenter(marker.getPosition());
if(map.zoom < 15)
map.setZoom(15);
marker.setIcon(icon.icon);
marker.setZIndex(google.maps.Marker.MAX_ZINDEX + 1);
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function downloadUrl(url, callback, map, infoWindow) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, map, infoWindow, request.status);
}
};
request.open('GET', url, true);
request.send();
}
function doNothing() {}
window.setInterval(function() {calldownloadUrl(url,map,infoWindow)},20000);
</script>
I've a similar app and I've also ran into similar behavior.
In my case, I've been updating an array of markers every 30 secs (for each marker: location, icon, content of a listener).
Firstly, I have stopped creating a new marker each update, I thought that setting markers[id].setMap(null); and creating new one will be OK, that CG will handle this.
Then I've changed the code to only update markers position, icon and listener, like this:
this.markers[id].setPosition(new google.maps.LatLng(lat, lng));
this.markers[id].setIcon(this.updateFlags(status, id));
google.maps.event.addListener(this.markers[id], 'mouseover', function () {
infoWindow.setContent(text);
infoWindow.open(this.map, this);
});
google.maps.event.addListener(this.markers[id], 'click', function () {
devices.selectDevice(index);
});
This produced much less consumed memory, but still...
Finally I've edited code like this:
this.markers[id].setPosition(new google.maps.LatLng(lat, lng));
this.markers[id].setIcon(this.updateFlags(status, id));
google.maps.event.clearListeners(this.markers[id], 'mouseover');
google.maps.event.clearListeners(this.markers[id], 'click');
google.maps.event.addListener(this.markers[id], 'mouseover', function () {
infoWindow.setContent(text);
infoWindow.open(this.map, this);
});
google.maps.event.addListener(this.markers[id], 'click', function () {
devices.selectDevice(index);
});
I've tested it in Chrome Developer Tools (F12) -> Profiler and Take Heap Snapshot. And you will see if it grows too fast.
So in your case it would mean adding this line as the first line of function bindinfoWindow():
google.maps.event.clearListeners(marker, 'click');
I think you need to empty the gmarkers array each time you calling that ajax request, or reset the i variable before you processing the received data. In this way you are not adding all the new markers to the previous ones, which seems is the bottleneck in your code.
P.S. I didn't test your code. I'm just guessing.
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.
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
I am trying to pass dynamic data from mysql then creating multiple markers on google.
Here is my html code.
<div ng-app="mapsApp" ng-controller="MapCtrl">
<div class="map">
<div id="map" style="width: 100%;height:738px;"></div>
</div>
</div>
Here is the angularjs Script.
//Angular App Module and Controller
var investup = angular.module('mapsApp', [])
investup.controller('MapCtrl', function ($scope, $compile) {
var cities = [
{
title: 'xyz',
city : '<img src="images/xxx.jpg" />',
lat : 12.2917925,
long : 76.6704174
},
{
title: 'Add to Cart',
city : '<button class="org-btn" ng-click="cartone()" style="display:block;font-size:12px;margin:0 auto 0 auto;">Add to Cart</button>',
lat : 12.2725645,
long : 76.6705986
},
];
//Define your locations: HTML content for the info window, latitude, longitude
var popup = [
['<img src="images/xyz.jpg" />'],
['<img src="images/xyz.jpg"/>'],
];
// Setup the different icons and shadows
var iconURLPrefix = 'http://maps.google.com/mapfiles/ms/icons/';
var icons = [iconURLPrefix + 'red-dot.png', iconURLPrefix + 'purple-dot.png']
var iconsLength = icons.length;
var mapOptions = {
zoom: 12,
center: new google.maps.LatLng(12.2982778, 76.6903664),
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
streetViewControl: false,
panControl: false,
zoomControlOptions: {
position: google.maps.ControlPosition.LEFT_BOTTOM
}
}
$scope.popup = popup;
$scope.map = new google.maps.Map(document.getElementById('map'), mapOptions);
var activeInfoWindow;
var activeInfoWindow2;
var iconCounter = 0;
$scope.markers = [];
for (i = 0; i < cities.length; i++) {
var createMarker = function (info) {
var marker = new google.maps.Marker({map: $scope.map,icon: icons[iconCounter],position: new google.maps.LatLng(info.lat, info.long),popup: popup[i][0]});
google.maps.event.addListener(marker, 'click', function() {
if(activeInfoWindow2 != null)
activeInfoWindow2.close();
var contentString = "<div><h2>" + info.city + "</h2></div>";
var compiled = $compile(contentString)($scope);
var infoWindow = new google.maps.InfoWindow({ content: compiled[0] });
infoWindow.open($scope.map, marker);
activeInfoWindow = infoWindow;
});
google.maps.event.addListener(marker, 'mouseover', function() {
var contentString = "<div><h2>" + marker.popup + "</h2></div>";
var compiled = $compile(contentString)($scope);
var infoWindow = new google.maps.InfoWindow({ content: compiled[0] });
infoWindow.open($scope.map, marker);
activeInfoWindow2 = infoWindow;
if(activeInfoWindow != null)
activeInfoWindow.close();
});
google.maps.event.addListener(marker, 'mouseout', function() {
if(activeInfoWindow2 != null)
activeInfoWindow2.close();
});
$scope.markers.push(marker);
}
createMarker(cities[i]);
iconCounter++;
}
$scope.openInfoWindow = function(e, selectedMarker) {
e.preventDefault();
google.maps.event.trigger(selectedMarker, 'click');
}
});
Here is the screenshot of the result
This is the static code when i'm placing php code in cities and popup section to not showing the result.
Problem is when i don't how to call php code in angularJS. Kindly help me.
Thanks in advance.
1- You probably would need to use a framework to handle JSON serialization for you.
For the sake of simplicity you can use this library (https://github.com/mevdschee/php-crud-api), and copy api.php to the server root directory.
2- Using $http:
investup.controller('MapCtrl', function($scope, $compile, $http) {
$http.get('/api.php/cities').success(function(response) {
var cities = response.cities;
// the rest of controller function body
}).catch(handleError);
})