Google maps centered load failure - google-maps

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;
}

Related

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 Map api V3, setPosition/setCenter is not working

There are two places where i need to show google maps.
I'm using same code for both maps(I mean I'm reusing same code for both maps).
Below are links where you can find screen shots of those two maps.
https://drive.google.com/file/d/0B2JnvvXsAALUdlVzemRVMzNMajF4OFB1V0JXc0RuN1p4eWFV/view - map1
https://drive.google.com/file/d/0B2JnvvXsAALUVGRhNm1HSldhQnpZT3k4S2I2R1YyQkp4OWZz/view - map2
I'm showing second map(map2) in bootstarp modal
first map(map1) is working fine. But in second map(map2), though I have used setCenter method, marker is not showing at center of the map(instead it is showing at top left corner).
what should i do to place marker at center of the map(in second map)?
below is my code..
initialize: function(options){
//initializing the geocoder
this.geocoder = new google.maps.Geocoder();
this.map;
},
//on show of the view
//onShow is a marionette method, which will be triggered when view is shown
onShow: function(){
var address = this.model.get("address");
//render the map with dummy latLang
this.renderMap();
//render the Map with Proper address
if(address!== ""){
this.renderMapWithProperAddress(address);
}
},
renderMap: function(){
var mapCanvas = document.getElementById("mapCanvas"), self = this,
mapOptions = {
center: new google.maps.LatLng(64.855, -147.833),//dummy latLang
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControl: false,
mapTypeControl: false,
streetViewControl:false
};
//initializing google map
self.map = new google.maps.Map(mapCanvas, mapOptions);
$("#myModal").on("shown.bs.modal",function(){
google.maps.event.trigger(self.map, "resize");
});
},
renderMapWithProperAddress: function(address){
var self = this,marker;
self.geocoder.geocode( { "address": address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
self.map.setCenter(results[0].geometry.location);
marker = new google.maps.Marker({
map: self.map,
position: results[0].geometry.location,
title: address
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
My guess, without seeing your code, is that you need to trigger a map resize event after the bootstrap modal has been shown.
Bootstrap modal
Maps events
$('#myModal').on('shown.bs.modal', function () {
google.maps.event.trigger(map, 'resize');
});
Edit:
Here is a complete and working example. As per my comment, you should 1) Trigger a map resize and 2) set the map center to your marker coordinates.
var center = new google.maps.LatLng(59.76522, 18.35002);
function initialize() {
var mapOptions = {
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: center
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var marker = new google.maps.Marker({
map: map,
position: center
});
}
$('.launch-map').on('click', function () {
$('#modal').modal({
backdrop: 'static',
keyboard: false
}).on('shown.bs.modal', function () {
google.maps.event.trigger(map, 'resize');
map.setCenter(center);
});
});
initialize();
JSFiddle demo

Google Map not loaded in second time in bootstrap modal

This script is creating a problem that when i used to load google map in bootstrap modal.
First time map is loaded but with second time map is not loaded fully.
<script>
var map = '';
function showmap(){
if(!map){
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(23.6459, 81.9217),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
var marker = new google.maps.Marker({
position: map.getCenter(),
map: map
});
google.maps.event.addListener(map, "click", function(){
document.getElementById("latitude").value = map.getCenter().lat();
document.getElementById("longitude").value = map.getCenter().lng();
marker.setPosition(map.getCenter());
//document.getElementById("zoom").value = map.getZoom();
});
google.maps.event.addListener(map, "center_changed", function(){
document.getElementById("latitude").value = map.getCenter().lat();
document.getElementById("longitude").value = map.getCenter().lng();
marker.setPosition(map.getCenter());
//document.getElementById("zoom").value = map.getZoom();
});
}
}
</script>
<script>
var map = '';
function showmap(){
if(!map){
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(23.6459, 81.9217),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
^^^^ Remove var from here and it works fine
var marker = new google.maps.Marker({
position: map.getCenter(),
map: map
});
google.maps.event.addListener(map, "click", function(){
document.getElementById("latitude").value = map.getCenter().lat();
document.getElementById("longitude").value = map.getCenter().lng();
marker.setPosition(map.getCenter());
});
}
}
</script>
in function when assigning map variable again in modal is creating problem so to remove conflict just remove var map when assingin it to google.maps
This is meant to be a comment but I am not allowed to add comments at this time.
I also experience the same in an MVC app. Modal content (resource title and map) is loaded as partial view from a controller action. First map loads nicely but next map(s) are clipped and only top left part shows. Using Bootstrap 3.
It is worth mentioning that if you refresh the page, the map loads well but that's not practical.

Google maps marker, with added directions code not showing

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

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;