I have no JavaScript or jQuery knowledge, I have no idea what to do with this Google Maps code.
I need to trigger this Google Maps resize code:
google.maps.event.trigger(map, 'resize');
The resize code above needs to be triggered after this waypoints is triggered below:
// Studio Page
jQuery('.studio-page').waypoint(function() {
jQuery('.kickass-studio').addClass( 'show animated bounceInLeft' );
jQuery('.location').addClass( 'show animated bounceInRight' );
jQuery('.geo-address').addClass( 'show animated bounceInDown' );
},
{
offset: '10%'
});
The above code is waypoints.js. My problem is that Google Maps breaks (you can only see the top left corner of the map). But from what I have found on Stack Overflow and other forums, this is due to the fact that the div is going from display: none to display: block after my waypoints plugin is done (adds class "show"). So I need to then trigger the Google Maps resize after waypoints is done adding those classes.
How would I go about doing this?
EDIT:
I have tried this:
// Studio Page
jQuery('.studio-page').waypoint(function() {
jQuery('.kickass-studio').addClass( 'show animated bounceInLeft' );
jQuery('.location').addClass( 'show animated bounceInRight' );
jQuery('.geo-address').addClass( 'show animated bounceInDown' );
var currCenter = map.getCenter();
google.maps.event.trigger(map, 'resize');
map.setCenter(currCenter);
},
{
offset: '10%'
});
But putting the above resize trigger there throws the Google Maps off my long and lat center point where my marker is?
EDIT:
Here is my maps script:
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
function initialize() {
var latlng = new google.maps.LatLng(-33.8333406,18.6470022);
directionsDisplay = new google.maps.DirectionsRenderer();
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
};
var map = new google.maps.Map(document.getElementById("map"),myOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById("directionsPanel"));
var marker = new google.maps.Marker({
position: latlng,
map: map,
title:"Get Directions"
});
}
function calcRoute() {
var start = document.getElementById("routeStart").value;
var end = "-33.8333406,18.6470022";
var request = {
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
if (status == 'ZERO_RESULTS') {
alert('No route could be found between the origin and destination.');
} else if (status == 'UNKNOWN_ERROR') {
alert('A directions request could not be processed due to a server error. The request may succeed if you try again.');
} else if (status == 'REQUEST_DENIED') {
alert('This webpage is not allowed to use the directions service.');
} else if (status == 'OVER_QUERY_LIMIT') {
alert('The webpage has gone over the requests limit in too short a period of time.');
} else if (status == 'NOT_FOUND') {
alert('At least one of the origin, destination, or waypoints could not be geocoded.');
} else if (status == 'INVALID_REQUEST') {
alert('The DirectionsRequest provided was invalid.');
} else {
alert("There was an unknown error in your request. Requeststatus: \n\n"+status);
}
}
});
}
Use these lines for centering your google map after resizing:
var currCenter = map.getCenter();
google.maps.event.trigger(map, 'resize');
map.setCenter(currCenter);
Related
I am creating direction service on google map. Everything is working fine.
I want to disable infowindow of origin(A) and destination(B) points only not marker's. How can I hide it or remove it?
Check this attached image for more details
Here is code for setup google map. It is written in angular.
$scope.directionsService.route({
origin: {'placeId': $scope.originPlaceId},
destination: {'placeId': $scope.destinationPlaceId},
travelMode: defaultTravelMode
},
function (response, status) {
if (status === 'OK') {
$scope.directionsDisplay.setDirections(response);
$scope.path = new google.maps.Polyline({
path: response.routes[0].overview_path
});
// filter stores by path
$scope.filterStoresByDirectionPath($scope.path);
}
});
//function to design infowindow of marker
$scope.newMarker = function (opts) {
let marker = new google.maps.Marker(opts);
marker.travelTime = opts.travelTime;
marker.timeValue = opts.timeValue;
marker.url = opts.url;
$scope._on({
obj: marker,
event: 'click',
callback: function () {
let content = 'Marker content';
if ($scope.infoWindow) {
$scope.infoWindow.close();
}
$scope.infoWindow = new google.maps.InfoWindow({content: content});
$scope.infoWindow.open($scope.map, marker);
}
});
I have an asp mvc project where the user is asked for geolocalization via google maps (API), so i had to use jquery 1.7.2 and save it's coordinates, but when i try to save them via ajax request i get this error on firebug and stops all the other code.
http://i47.photobucket.com/albums/f195/warbandit69/ErrorKambi1_zpsac3979f4.png
As you can see the error is very unacurte with it's description, and here is the function on jquery that makes that call
function ReviewAtEnd() {
if (typeof (idserialF) != "undefined" && idserialF != null) {
var datax = { idjob: idjobx, latitud: Latitud, longitud: Longitud, coordinates: coordenadasGM };
var urlx = "/JOBS/PROG41/FailedItemOnSite";
$.ajax({
type: "POST",
url: urlx,
data: datax,
async: false,
success: function (data) {
mostrar_alert_ui(data.titulo, data.mensaje, 350);
if (data.success) {
AfterPassedTest();
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Failed " + urlx);
alert(xhr.responseText);
alert(thrownError);
}
});
}
}
UPDATE
Here is the google maps function i missed to show you
var Latitud;
var Longitud;
var coordenadasGM;
function showMap() {
//If HTML5 Geolocation Is Supported In This Browser
if (navigator.geolocation) {
//Use HTML5 Geolocation API To Get Current Position
navigator.geolocation.getCurrentPosition(function (position) {
//Get Latitude From Geolocation API
var latitude = position.coords.latitude;
Latitud = latitude;
//Get Longitude From Geolocation API
var longitude = position.coords.longitude;
Longitud = Longitud;
//Define New Google Map With Lat / Lon
var coords = new google.maps.LatLng(latitude, longitude);
coordenadasGM = coords;
//Specify Google Map Options
var mapOptions = {
zoom: 15,
center: coords,
mapTypeControl: true,
navigationControlOptions: { style: google.maps.NavigationControlStyle.SMALL }, mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("mapContainer"), mapOptions);
var marker = new google.maps.Marker({
position: coords,
map: map,
title: "You Are Here!"
});
}
);
} else {
//Otherwise - Gracefully Fall Back If Not Supported... Probably Best Not To Use A JS Alert Though :)
mostrar_alert_ui("WARNING", "Geolocation API is not supported in your browser.", 350)
}
}
//Once Page Is Populated - Initiate jQuery
$(document).ready(function () {
//Show The Map
showMap();
// When The Viewing Window Is Resized
$(window).resize(function () {
//CSS Resizes Container So Lets Recall The Map Function
showMap();
});
});
Jsfiddle here -> http://jsfiddle.net/ricardojriosr/9mzss1ud/
In google map api when i drag a route, route drags, but when i leave mouse click route goes to it's old position.
Can anyone tell me what's the reason behind this.
I can't show you all code, But here is some code:-
var rendererOptions = {
map: map,
suppressMarkers : true,
preserveViewpoint: true,
polylineOptions:{strokeColor:'blue',clickable:true},
draggable: true
};
var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
var directionsService = new google.maps.DirectionsService();
and
directionsService.route(request, function(result, status) {
if(start!=end)
{
if (status == google.maps.DirectionsStatus.OK)
{
directionsDisplay.setOptions({ preserveViewport: true });
directionsDisplay.setDirections(result);
google.maps.event.addListener(directionsDisplay, 'directions_changed',function () {
});
}
}
});
Got it. way points has same coordinates when i drag.
Thank you for help
The goal
Reuse already loaded JavaScript correctly.
The problem
I'm generating a map dynamically using Google Maps API V3 and I need to reuse it. How?
The scenario
On Index.html, there's the following script:
var gMapsLoaded = false;
window.gMapsCallback = function () {
gMapsLoaded = true;
$(window).trigger('gMapsLoaded');
}
window.loadGoogleMaps = function () {
if (gMapsLoaded) return window.gMapsCallback();
var script_tag = document.createElement('script');
script_tag.setAttribute("type", "text/javascript");
script_tag.setAttribute("src",
"http://maps.google.com/maps/api/js?sensor=false&callback=gMapsCallback");
(document.getElementsByTagName("head")[0]
|| document.documentElement).appendChild(script_tag);
}
When I click on some button to show the map, my app invokes this script:
[...]
var geocoder;
var map;
var address = context.address();
function initialize() {
var mapDiv = document.getElementById("map_canvas");
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 15,
center: latlng,
mapTypeControl: true,
mapTypeControlOptions:
{ style: google.maps.MapTypeControlStyle.DROPDOWN_MENU },
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(mapDiv, myOptions);
if (geocoder) {
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
map.setCenter(results[0].geometry.location);
var infowindow = new google.maps.InfoWindow(
{
content: '<b>' + address + '</b>',
size: new google.maps.Size(150, 50)
});
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title: address
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.open(map, marker);
});
} else {
alert("No results found");
}
} else {
alert
("Geocode was not successful
for the following reason: " + status);
}
});
}
gMapsLoaded = false;
}
$(window).on('gMapsLoaded', initialize);
window.loadGoogleMaps();
As you can see, the application is always calling the loadGoogleMaps(); function that calls the external .js file. If I click in the 5 different maps, I get 5 scripts with the same proposal.
Someone have any idea to solve this?
Duplicated question?
Yes, I think that the essence of the question is duplicated, but the nucleus isn't.
As you can see, the application is always calling the
loadGoogleMaps(); function that calls the external .js file. If I
click in the 5 different maps, I get 5 scripts with the same proposal.
That is incorrect. After the first time it completely loads, the if statement on the first line will return early, preventing you from including it multiple times.
There's nothing wrong with the way that's written.
jsFiddle
var gMapsLoaded = false;
window.gMapsCallback = function () {
gMapsLoaded = true;
$(window).trigger('gMapsLoaded');
}
window.loadGoogleMaps = function () {
if (gMapsLoaded) return window.gMapsCallback();
console.log('Generating new script tag');
var script_tag = document.createElement('script');
script_tag.setAttribute("type", "text/javascript");
script_tag.setAttribute("src",
"http://maps.google.com/maps/api/js?sensor=false&callback=gMapsCallback");
(document.getElementsByTagName("head")[0]
|| document.documentElement).appendChild(script_tag);
}
$(window).on("gMapsLoaded",function(){
console.log("gMapsLoaded");
});
$(function(){
$("button").on("click",window.loadGoogleMaps);
});
Now, if you were to click it 5 times really fast when it isn't already loaded, it could potentially load it multiple times. You should call that function on it's own before a click event would normally happen to prevent that.
Update:
At the end of your initialize() method, you're using gMapsLoaded = false; which causes the above code to once again request a new script tag. Simply remove/comment out that line.
I wonder whether someone may be able to help me please.
Because of loading issues, I've moved the map options code to my HTML form, rather than it being in a separate Javascript file.
The problem is that I now can't get the Geocode functionality to work. I've added my code below. I'm sure it must be something simple, but I'm a little perplexed by this. I just wondered whether it would be at all possible please that someone could let me know where I've gone wrong.
Many thanks
function geocode() {
// This is defining the global variables
var geocoder, marker;
// This is making the link with the 'Search For Location' HTML form
var form = document.getElementById('searchforlocationform');
// This is catching the forms submit event
form.onsubmit = function() {
// This is getting the Address from the HTML forms 'Address' text box
var address = document.getElementById('inputaddress').value;
// This is making the Geocoder call
getCoordinates(address);
// This is preventing the form from doing a page submit
return false;
}
}
function geocodePosition(pos) {
geocoder.geocode({
latLng: pos
},
function(responses) {
if (responses && responses.length > 0) {
updateMarkerAddress(responses[0].formatted_address);
} else {
updateMarkerAddress('Cannot determine address at this location.');
}
});
}
//New Code
function updateMarkerStatus(str) {
document.getElementById('markerStatus').innerHTML = str;
}
//Changed 'address' to 'returnedaddress'
function updateMarkerAddress(str) {
document.getElementById('returnedaddress').value= str;
}
// This creates the function that will return the coordinates for the address
function getCoordinates(address) {
// This checks to see if there is already a geocoded object. If not, it creates one
if(!geocoder){geocoder = new google.maps.Geocoder();}
// This is creating a GeocoderRequest object
var geocoderRequest = {address: address}
// This is making the Geocode request
geocoder.geocode(geocoderRequest, function(results, status) {
// Check if status is OK before proceeding
if (status == google.maps.GeocoderStatus.OK) {
// Center the map on the returned location
map.setCenter(results[0].geometry.location);
// Check to see if we've already got a Marker object
if (!marker) {
map.setZoom(16);
marker = new google.maps.Marker({
map: map, draggable:true
});
}
// Setting the position of the marker to the returned location
marker.setPosition(results[0].geometry.location);
// Add dragging event listeners.
google.maps.event.addListener(marker, function() {
updateMarkerAddress;
});
//This fills out the 'Latitude' and 'Longitude' text boxes on the HTML form
document.getElementById('osgb36lat').value= results[0].geometry.location.lat();
document.getElementById('osgb36lon').value= results[0].geometry.location.lng();
//This allows the marker to be draggable and tells the 'Latitude' and 'Longitude' text boxes on the HTML form to update with the new co-ordinates as the marker is dragged
google.maps.event.addListener(marker,'dragend',
function() {
updateMarkerStatus;
geocodePosition(marker.getPosition());
document.getElementById('osgb36lat').value = marker.position.lat();
document.getElementById('osgb36lon').value = marker.position.lng();
});
// Update current position info.
latLng = [marker.position.lat(), marker.position.lng()].join(', ');
geocodePosition(marker.getPosition());
var point = marker.getPosition();
map.panTo(point);
}
}
)
}
<script type="text/javascript">
(function() {
window.onload = function(){
var latlng = new google.maps.LatLng(54.312195845815246,-4.45948481875007);
var options = {
zoom: 6,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
position: google.maps.ControlPosition.TOP_RIGHT
},
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.ZOOM_PAN,
position: google.maps.ControlPosition.TOP_LEFT
},
scaleControl: true,
scaleControlOptions: {
position: google.maps.ControlPosition.BOTTOM_LEFT
}
};
var map = new google.maps.Map(document.getElementById('map'), options);
}
})();
</script>
You seen to be trying to call updateMarkerAddress with updateMarkerAddress; and updateMarkerStatus with updateMarkerStatus;, here you are missing (/*some param*/).
What are the loading issues? Maybe if you show your html someone could help with that too.