Google maps marker, with added directions code not showing - google-maps

I seem to be having trouble adding a marker to one of my maps that I have created and I just can't seem to figure out where I am going wrong with it.
The map has been added to the site fine, and I even have the directions code working which happens to be displaying markers.
What I would like would be an initial marker to display where, in this case, the school is and have an info box on click to show the address but I just can't seem to get it displaying no matter what I try.
My code for everything is as follows:-
<div id="map_canvas" style="width:100%; height:392px;float:left;"></div>
<div id="directionsPanel" style="float:left;max-width:395px; overflow:scroll;overflow-x: hidden;"></div>
<script>
//define one global Object
var myMap = {}
//init
function initialize(){
//set up map options
var mapOptions = {
center: new google.maps.LatLng(53.964304,-2.028522),
zoom: 15,
scrollwheel: false,
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
myMap.map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
myMap.directionsService = new google.maps.DirectionsService();
myMap.directionsDisplay = new google.maps.DirectionsRenderer();
myMap.directionsDisplay.setMap(myMap.map);
myMap.directionsDisplay.setPanel(document.getElementById("directionsPanel"));
}//end init
function createMarker(point, title, content, map) {
var marker = new google.maps.Marker({
position: point,
map: map,
title: title
});
var infowindow = new google.maps.InfoWindow({
content: content
});
google.maps.event.addListener(marker, 'click', function() {
if(curr_infw) { curr_infw.close();} // We check to see if there is an info window stored in curr_infw, if there is, we use .close() to hide the window
curr_infw = infowindow; // Now we put our new info window in to the curr_infw variable
infowindow.open(map, marker); // Now we open the window
});
return marker;
}
//directions
var calcRoute = function() {
var start = document.getElementById("start").value,
end = document.getElementById("end").value,
request = {
origin:start,
destination:end,
durationInTraffic :true,
transitOptions: {
departureTime: new Date()
},
provideRouteAlternatives : true,
travelMode: document.getElementById("travelmode").value
};
myMap.directionsService.route(request, function(result, status) {
if(status == google.maps.DirectionsStatus.OK) {
myMap.directionsDisplay.setDirections(result);
}else{
alert("something went wrong!");
}
});
}
//script loader
var loadScript = function() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.googleapis.com/maps/api/js?key=AIzaSyDZsY0Xbo137bDtb8wmefTogdGl82QM85s&sensor=false&callback=initialize";
document.body.appendChild(script);
}
window.onload = loadScript;
Any help on this guys would be greatly appreciated before I end up becoming bald from pulling out all my hair lol.
Jason

Related

Show User location on google maps

First thing is I will tell you I am new to google maps and some of it is very confusing to me. What I need to do is show a users location and have the appropriate markers show up. I have the database all ready and somewhat of the Google map.
What I am working with is an example from here. What I can either get is the markers if I use a static LatLng or just the users dynamic location with no markers.
Need help please. And if you downvote this post please let me know why.
Code I am using can be found at https://jsfiddle.net/8q1apmdy/9/ and show where in the blow code is where I am missing something, most likely small or in the wrong position.
function initMap() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
});
var map = new google.maps.Map(document.getElementById('map'), {
center: pos,
zoom: 12
});
}
a) While running your code locally, I was getting 'pos' undefined, so I moved the following code 'var map = new google.maps.Map(..' inside the getCurrentPosition(){...
b) Then I got another error ' InvalidValueError: setMap: not an instance of Map;' so created a 'var map' globally.
Loaded the map successfully, but still markers were not loaded. while debugging your code at this point 'var marker = new google.maps.Marker({...' it is iterating for all markers from xml but somehow markers are not adding to the map..dont know the reason yet?
So I have tried in a different way. Please see all markers from xml displayed on map. Here I am just getting the 'name' in marker, you might need to add other parameters like id, address etc.
JSFiddle added for reference
var infowindow;
var map;
//var downloadUrl;
function initialize() {
var mapOptions = {
zoom: 12,
center: new google.maps.LatLng(-33.868820, 151.209290),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map'), mapOptions);
downloadUrl("https://storage.googleapis.com/mapsdevsite/json/mapmarkers2.xml", function(data) {
var bounds = new google.maps.LatLngBounds();
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName('marker');
for (var i = 0; i < markers.length; i++) {
var id = markers[i].getAttribute('id');
var address = markers[i].getAttribute('address');
var type = markers[i].getAttribute('type');
var latlng = new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
bounds.extend(latlng);
var marker = createMarker(id, markers[i].getAttribute("name"), address, latlng, type);
}//finish loop
//map.fitBounds(bounds);
}); //end downloadurl
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
}
function createMarker(id, name, address, latlng, type) {
var marker = new google.maps.Marker({
position: latlng,
map: map
});
google.maps.event.addListener(marker, "click", function() {
if (infowindow) infowindow.close();
infowindow = new google.maps.InfoWindow({content: name});
infowindow.open(map, marker);
});
return marker;
}
JSFiddle

Problems with geolocation

I want to make an application that shows your current position on a map with a marker. The code I've done seems to work but it doesn't display the marker. Can someone help me, please?
Here's my app.js:
var app = angular.module('starter', ['ionic', 'ngCordova']);
app.run(function($ionicPlatform) {
$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();
}
});
});
app.controller('MapController', function($scope, $cordovaGeolocation, $ionicLoading, $ionicPlatform) {
$ionicPlatform.ready(function() {
$ionicLoading.show({
template: '<ion-spinner icon="bubbles"></ion-spinner><br/>Acquiring location!'
});
var posOptions = {
enableHighAccuracy: true,
timeout: 20000,
maximumAge: 0
};
$cordovaGeolocation.getCurrentPosition(posOptions).then(function(position) {
var lat = position.coords.latitude;
var long = position.coords.longitude;
var myLatlng = new google.maps.LatLng(lat, long);
var mapOptions = {
center: myLatlng,
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
$scope.map = map;
$ionicLoading.hide();
}, function(err) {
$ionicLoading.hide();
console.log(err);
});
google.maps.event.addListener($scope.map, 'idle', function() {
var marker = new google.maps.Marker({
map: $scope.map,
position: new google.map.LatLng(myLatlng)
icon:'http://i.imgur.com/fDUI8bZ.png'
});
var infoWindow = new google.maps.InfoWindow({
content: "Here I am!"
});
google.maps.event.addListener(marker, 'click', function() {
infoWindow.open(map, marker);
});
infowindow.open(map, marker);
});
})
});
You are using
var long = position.coords.longitude;
whereas long is a keyword in javascript. Check the link below.
https://www.w3schools.com/js/js_reserved.asp
Unless you are using ECMAScript 5/6 standard
Try to add Latitude and Longitude in following way to new google.map.LatLng(...)
var marker = new google.maps.Marker({
map: $scope.map,
position: new google.map.LatLng(lat, long)
icon:'http://i.imgur.com/fDUI8bZ.png'
});
Hope this will help to you
Spent a very hair-tearing hour or so trying to get the good old W3C geolocation example to work in my particular application. Didn't see this:
https://developers.google.com/web/updates/2016/04/geolocation-on-secure-contexts-only
If you are NOT using https you may (will?) get a silent, non-functioning outcome, both in Chrome and Firefox! As soon as I switched to https, it was fine.

Google maps centered load failure

Well I'm having this problem, load the map once and everything works perfect. The second time or once update the map does not load ok, but not centered load when navigating on you can see the marks that are made but is deformed or simply lost.
I have tried several ways to solve this problem, first and most common I found was to use google.maps.event.trigger(map 'resize') but it did not work then and logic, try that whenever loading map is executed, create a new map, with the same data and focused but neither worked for me. It may be also the way I use the map. I am using the plugin of the camera in my application, the user takes a photo and this should detect where I draw the picture and display the map. Each time the view is opened, the plug of the camera, in the process of taking and show the picture is where I call the appropriate functions to load the map and this has me a bit tricky immediately loaded I have a good time locked in this problem, I found solutions serve me but only for the browser, the device does not work. I am using ionic framework and plugins cordova.
Controller :
.controller("CamaraCtrl", function($scope,$rootScope, Camera,$cordovaGeolocation,$state,$location,$ionicSideMenuDelegate) {
var posOptions = {timeout: 10000, enableHighAccuracy: false};
$cordovaGeolocation
.getCurrentPosition(posOptions)
.then(function (position) {
var latitud_actual = position.coords.latitude
var longitud_actual = position.coords.longitude
$scope.latitud = latitud_actual;
$scope.longitud = longitud_actual;
//$scope.map = new google.maps.Map(document.getElementById("mapa_ubicacion"), mapOptions);
}, function(err) {
// error
});
function initialize() {
var mapOptions = {
center: new google.maps.LatLng($scope.latitud, $scope.longitud),
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false
};
var map = new google.maps.Map(document.getElementById("map"),
mapOptions);
$scope.setMarker(map, new google.maps.LatLng($scope.latitud, $scope.longitud), 'Yo', '');
$scope.map = map;
}
$scope.setMarker = function(map, position, title, content) {
var marker;
var markerOptions = {
position: position,
map: map,
title: title
};
marker = new google.maps.Marker(markerOptions);
google.maps.event.addListener(marker, 'click', function () {
// close window if not undefined
if (infoWindow !== void 0) {
infoWindow.close();
}
// create new window
var infoWindowOptions = {
content: content
};
infoWindow = new google.maps.InfoWindow(infoWindowOptions);
infoWindow.open(map, marker);
});
}
$scope.mostrar_form = false;
$scope.mostrar_boton_view = false;
$scope.getPhoto = function() {
Camera.getPicture().then(function(imageURI) {
console.log(imageURI);
$scope.lastPhoto = imageURI;
$scope.mostrar_form = true;
$scope.mostrar_boton_view = false;
google.maps.event.addDomListener(window, 'load', initialize);
initialize();
}, function() {
$scope.mostrar_boton_view = true;
}, {
quality: 75,
targetWidth: 320,
targetHeight: 320,
saveToPhotoAlbum: false
});
};
$scope.getPhoto();
})
The only solution I found was to create a function that executes the map again. It should not be as optimal but at least it solved my problem.
$scope.centrar = function(){
var mapOptions = {
center: new google.maps.LatLng($scope.latitud, $scope.longitud),
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false
};
var map = new google.maps.Map(document.getElementById("map"),
mapOptions);
$scope.setMarker(map, new google.maps.LatLng($scope.latitud, $scope.longitud), 'Yo', '');
$scope.map = map;
}

Google Maps API v3 map not loading completely

I am having some difficulty with a google map. The problem is that only a small portion of the map is loading as shown here:
After the page loads, if I resize the browser even the slightest amount, this causes the complete map to refresh and load correctly, as shown here:
Here is my javascript code:
google.maps.event.addDomListener(window, 'load', initialize);
$(document).ready(function(){
var $width = document.getElementById("propertysection").offsetWidth;
$('#map-canvas-2').width($width-28-175);
$('#map-canvas-2').height($width);
$('#myGridMap').height($width);
});
function initialize() {
var map;
var propertyMap;
var marker;
var infowindow;
var myOptions = {
zoom: 6,
center:new google.maps.LatLng(50.7,-86.05),
mapTypeId: google.maps.MapTypeId.HYBRID
}
map = new google.maps.Map(document.getElementById("map-canvas-2"),myOptions);
infowindow = new google.maps.InfoWindow({
content: 'Property Info',
position: new google.maps.LatLng(0, 0)
});
}
Can anyone suggest what the problem might be? Thanks.
You shouldn't mix the jquery ready method with the window load event (see http://api.jquery.com/ready/).
Instead, call initialize from within your .ready function, or place the window resize functions in the initialize method itself (before initializing the map).
I am using bootstrap and a mega menu and I resolved it with using the official Google Maps API asynchronous load function. https://developers.google.com/maps/documentation/javascript/tutorial#asynch
function initialize() {
var myLatLng = new google.maps.LatLng(37.4221147, -122.0867373);
var map_canvas = document.getElementById('map_canvas');
var map_options = {
center: new google.maps.LatLng(37.4221147, -122.0867373),
zoom: 12,
mapTypeControl: false,
panControl: false,
zoomControlOptions: {
position: google.maps.ControlPosition.LEFT_CENTER
},
streetViewControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(map_canvas, map_options);
var contentString =
'<b>Google Gate Bridge</b>' +
'<p>Mountain View, CA 94043, USA</p>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
});
google.maps.event.addListener(marker, 'click', function(){
infowindow.open(map,marker);
});
}
function loadScript() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize";
document.body.appendChild(script);
}
var tab = document.getElementById('YourHtmlObjectID');
YourHtmlObjectID.onmouseover = loadScript;
YourHtmlObjectID.onclick = loadScript;

Google Maps API InfoWindow not Displaying content

My Code looks like this:
var map = /*some google map - defined earlier in the code*/;
var geocoder = new google.maps.Geocoder();
var address = 'Some Address, Some Street, Some Place';
geocoder.geocode({'address':address},function(results,status){
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var infobox = new google.maps.InfoWindow({
content: 'Hello world'
});
for(i in results){
var marker = new google.maps.Marker({
map: map,
position: results[i].geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infobox.setContent('blablabla');
infobox.open(map,marker);
alert(infobox.content); //displays 'blablabla'
});
}
}
});
Basically it's creating some markers on a single map based on a given address-string. It adds an infoWindow to the markers that opens on click.
Problem is: the infoWindow displays empty.
Screenshot here:
PS: Using Maps API V3
I just ran into the same problem, and found the very simple cause of it: The text in the info window was actually displayed, but in white color, and therefore just not visible on the white background. Giving the content a different color via CSS solved the problem for me.
Basically you need to use a function external to your marker adding-loop to add the infobox message to each marker... for an example and detailed explanation see:
http://code.google.com/apis/maps/documentation/javascript/events.html#EventClosures
Here is how I have done it.
var map,markersArray,infowindow; //infowindow has been declared as a global variable.
function initialize(){
var myOptions = {
zoom: 14,
center: new google.maps.LatLng(51.5001524,-0.1262362),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
infowindow = new google.maps.InfoWindow(
{
size: new google.maps.Size(150,50)
});
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
markersArray = [];
}
function createMarker(latlng, html,zoom) {
var contentString = html;
var marker = new google.maps.Marker({
position: latlng,
map: map,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
marker.MyZoom = zoom;
return marker;
}
You can find the working example here and the complete javascript here.
I have resolved issue by adding below code.
setTimeout(function () { GeocodeMarker.info.open(GoogleMap,
GeocodeMarker); }, 300);
Thanks