Google Maps will not show inside my div id="map" - google-maps

I am following a tutorial that can locate a friend (their mobile) and pinpoint them on a Google map. All was going well including getting my coordinates and printing them to screen and putting them inside my <div id="location"></div> but now I am trying to take those coords and mark them on a map but I cant get the map to show. I'm sure my functions are set up wrong somehow but I can't work it out. Any clues?
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.1/jquery.mobile-1.1.1.min.css" />
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.1.1/jquery.mobile-1.1.1.min.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script src="scripts/jquery.ui.map.js"></script>
<script>
$(document).ready(function(){
navigator.geolocation.getCurrentPosition(useposition);
});
</script>
<script>
function useposition(position){
lat = position.coords.latitude;
lon = position.coords.longitude;
$("#location").html('Lat: ' + lat + '<br />Lon: ' + lon);
};
function deviceposition(position){
$("#map").gmap({'center': deviceposition, 'zoom': 12, 'disableDefaultUI': true, 'mapTypeId': 'terrain'}).bind('init', function(ev, map) { themap = map;});
$('#map').gmap('addMarker', { 'id': 'client', 'position': deviceposition, 'bounds': true
});
}
</script>
</head>
<body>
<div id="location"></div>
<div id="map" style="width:400px; height:400px"></div>
<!-- This is supposed to be filled with the Google Map coords -->
</body>
</html>

I have tried passing div in CreateElement() method and then assigning the values to a variable mapcanvas. This whole declaration is inside a method which is called in this particular line:
navigator.geolocation.getCurrentPosition(success);
I am sharing the whole code..
<script>
function success(position) {
var mapcanvas = document.createElement('div');
mapcanvas.id = 'mapcontainer';
mapcanvas.style.height = '400px';
mapcanvas.style.width = '600px';
document.querySelector('article').appendChild(mapcanvas);
var coords = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var options = {
zoom: 15,
center: coords,
mapTypeControl: false,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("mapcontainer"), options);
var marker = new google.maps.Marker({
position: coords,
map: map,
title:"You are here!"
});
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success);
} else {
error('Geo Location is not supported');
}
</script>
Hope this would help!!!

Related

Angular ui-map (google map) residing in html partial and hidden with ng-if does not add markers

I hide the map-element initially using ng-if. When the ng-if evaluates to true I cannot add markers to the map. The map-element is contained in a html partial - it is not part of the initial html-page.
HTML:
<div ng-controller="MapCtrl">
<div style="width:100%;height:300px" ng-if="whatever">
<div ng-repeat="marker in myMarkers" ui-map-marker="myMarkers[$index]"
ui-event="{'map-click': 'openMarkerInfo(marker)'}">
</div>
<div id="map_canvas" ui-map="myMap" class="map"
ui-event="{'map-click': 'addMarker($event, $params)', 'map-zoom_changed': 'setZoomMessage(myMap.getZoom())' }"
ui-options="mapOptions">
</div>
</div>
<div style="width:100%;height:300px;background:yellow" ng-click="showMap()">
</div>
</div>
JS:
angular.module('doc.ui-map', ['ui.map','ngRoute'])
.controller('MapCtrl', ['$scope','$timeout', function ($scope,$timeout) {
$scope.myMarkers = [];
$scope.mapOptions = {
center: new google.maps.LatLng(35.784, -78.670),
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
$scope.addMarker = function ($event, $params) {
console.log('addMarker');
$scope.myMarkers.push(new google.maps.Marker({
map: $scope.myMap,
position: $params[0].latLng
}));
};
$scope.setZoomMessage = function (zoom) {
$scope.zoomMessage = 'You just zoomed to ' + zoom + '!';
console.log(zoom, 'zoomed');
};
$scope.openMarkerInfo = function (marker) {
$scope.currentMarker = marker;
$scope.currentMarkerLat = marker.getPosition().lat();
$scope.currentMarkerLng = marker.getPosition().lng();
$scope.myInfoWindow.open($scope.myMap, marker);
};
$scope.showMap = function(){
$scope.whatever = true;
}
$scope.setMarkerPosition = function (marker, lat, lng) {
marker.setPosition(new google.maps.LatLng(lat, lng));
};
}]) ;
The 'ng-if' directive will create or remove a portion of DOM based on expression. The ng-if expression is equal to false when you launch the map app.
So the map-ui element does't append to DOM tree and the 'myMap' property won't be added to the controller scope. This will make addMarker() broken because $scope.myMap === undefined
You could try to add the following code to your addMarker function and it should show undefined on your console:
console.log($scope.myMap);
Although ng-show caused the wrong map width/height problem, you could enforce map refresh by dispatching "resize" event when initialize the map.
You need to trigger a event "resize" on Google map object when you want to refresh the map.
google.maps.event.trigger(map,"resize");
My Example:
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Angular UI Map</title>
</head>
<body>
<div id="map" ng-controller="mapCtrl">
<input type="button" ng-click="showMap()"/>
<div ng-show="isShow">
<div id="map_canvas" ui-map="myMap" style="height:200px;width:300px" ui-event="{'map-click':'addMarker($event, $params)'}" ui-options="mapOptions">
</div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<script src="js/angular-ui-utils/modules/event/event.js"></script>
<script src="js/angular-ui-map/src/map.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=onGoogleReady"></script>
<script src="js/angularUIMap.js"></script>
<script>
function onGoogleReady(){
angular.bootstrap(document.getElementById("map"),['mapApp']);
}
</script>
</body>
</html>
angularUIMap.js
angular.module("mapApp",['ui.map'])
.controller("mapCtrl",function($scope,$timeout){
var mapInitFlag = false;
$scope.showMap = function(){
$scope.isShow = !$scope.isShow;
if(!mapInitFlag)
{
$timeout(function(){
google.maps.event.trigger($scope.myMap,'resize');
mapInitFlag=true;
console.log('adjust map');
});
}
};
$scope.myMarkers = [];
$scope.mapOptions = {
center: new google.maps.LatLng(35.784, -78.670),
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
$scope.addMarker = function ($event, $params){
$scope.myMarkers.push(new google.maps.Marker({
map: $scope.myMap,
position: $params[0].latLng
}));
};
});
Screenshot:
Hope this helpful.

Multiple Google Maps on same page

I have seen some topics about this on this forum but didn't get the answer I was looking for.
If I'm using such a code:
<script type="text/javascript">
(function() {
window.onload = function(){
var pinkParksStyles = '';
var pinkMapType = new google.maps.StyledMapType(pinkParksStyles,
{name: "Our Location"});
var mapOptions = {
zoom: 11,
center: new google.maps.LatLng(41.3850639,2.1734035),
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'pink_parks']
}
};
var map = new google.maps.Map(document.getElementById('map_canvas1'), mapOptions);
map.mapTypes.set('pink_parks', pinkMapType);
map.setMapTypeId('pink_parks');
var marker = new google.maps.Marker({
position: new google.maps.LatLng(41.3850639,2.1734035),
map: map
});
}
})();
</script>
<script type="text/javascript">
(function() {
window.onload = function(){
var pinkParksStyles = '';
var pinkMapType = new google.maps.StyledMapType(pinkParksStyles,
{name: "Our Location"});
var mapOptions2 = {
zoom: 11,
center: new google.maps.LatLng(41.3850639,2.1734035),
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'pink_parks']
}
};
var map2 = new google.maps.Map(document.getElementById('map_canvas2'), mapOptions2);
map2.mapTypes.set('pink_parks', pinkMapType);
map2.setMapTypeId('pink_parks');
var marker2 = new google.maps.Marker({
position: new google.maps.LatLng(41.3850639,2.1734035),
map: map2
});
}
})();
</script>
So I have two divs with ID map_canvas1 and map_canvas2. But only the second one gets shown. I have this imported in the header of the document: http://maps.google.com/maps/api/js?sensor=false
I need to make both work but with seperated javascript. Did manage it with getting all into same function, but I need it to be seperated.
Any advice?
THANKS!
make two seperate javascript functions out of it, and put both in the onload function.
Like this:
window.onload = function(){
function1(variable);
function2(variable);
}
function1(variable) {
do stuff;
}
function2(variable)
do other stuff;
}
Alternatively you could use jQuery to handle the onload, i think that can actually add multiple handlers to the body onload. See also http://api.jquery.com/ready/
javascriptmap.php?map=xxx
$(function() {
$("#divID").each( function() {
showMap(divID);
});
});
showMap(divID) {
show map on #divID
};
On the html/php file:
<script scr="javascriptmap.php?map=map1" />
<script scr="javascriptmap.php?map=map2" />

Google maps v3 zoom to GroundOverlay after load

Hi I am trying to load image on google maps. Here is what I get:
red square - what I see.
green square - what I want to see. I want to zoom to green square after map loads, but I cant manage to do that, any help?
Code:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
</head>
<body>
<div id="map" style="width: 800px; height: 400px;"></div>
<script type="text/javascript">
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 2,
center: new google.maps.LatLng(0, 0),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var imageBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(-90,-180),
new google.maps.LatLng(90,180));
var oldmap = new google.maps.GroundOverlay("http://www.dxatlas.com/HamCap/3Y0X/20UT-21MHz.gif", imageBounds);
oldmap.setMap(map);
oldmap.setOptions({opacity: 0.5});
map.fitBounds(imageBounds);
</script>
</body>
</html>
I want to zoom to overlay layer that map would look nice like green square shows, it looks like "map.fitBounds(imageBounds);" doesnt work...
Any ideas?
This may be the nature of Google Maps v3; bounding extent is out of range at -180 to 180, modifying longitude to 179.9999. Ensuring image bounds is within Google Maps global extent may solve problem.
http://jsfiddle.net/wptc/cPcMC/
Some code demonstrates the issue:
<html>
<head>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
</head>
<body>
<div id="map" style="width: 95%; height: 400px;"></div>
<script type="text/javascript">
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(30, -97),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var viewportBox;
google.maps.event.addListener(map, 'idle', function(event) {
var imageBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(-90,-179.999),
new google.maps.LatLng(90,180));
var oldmap = new google.maps.GroundOverlay("http://www.dxatlas.com/HamCap/3Y0X/20UT-21MHz.gif", imageBounds);
oldmap.setMap(map);
oldmap.setOptions({opacity: 0.5});
map.fitBounds(imageBounds);
var bounds = map.getBounds();
var ne = bounds.getNorthEast();
var sw = bounds.getSouthWest();
var viewportPoints = [
ne, new google.maps.LatLng(ne.lat(), sw.lng()),
sw, new google.maps.LatLng(sw.lat(), ne.lng()), ne
];
if (viewportBox) {
viewportBox.setPath(viewportPoints);
} else {
viewportBox = new google.maps.Polygon({
path: viewportPoints,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 1
});
viewportBox.setMap(map);
};
var info = document.getElementById('info');
info.innerHTML = 'NorthEast: ' + ne.lat() + ' ' + ne.lng() +
'<br />' + 'SouthWest: ' + sw.lat() + ' ' + sw.lng();
});
</script>
</body>
<div id='info'></div>
</html>​

Cannot locate user error when using html5 Geolocation

This is my code to get current location using Geolocation property of HTML5,
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="html5_init.js" id="html5_init"></script>
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script type="text/javascript">
function TestGeo()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition( TestMap, error ,{maximumAge: 30000, timeout: 10000, enableHighAccuracy: true} );
}
else
{
alert("Sorry, but it looks like your browser does not support geolocation.");
}
}
var map;
function TestMap(position)
{
//var latitude = position.coords.latitude;
//var longitude = position.coords.longitude;
//alert("Your coordinates are " + position.coords.latitude + ", " + position.coords.longitude);
var coords = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var mapOptions =
{
zoom: 10,
center: coords,
mapTypeControl: false,
navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var marker = new google.maps.Marker({ position: coords, map: map, title: "Your current location!" });
}
function error()
{
alert("Cannot locate user");
}
</script>
</head>
<body>
<form name="myform">
<input type="button" value="Geolocation" onclick="TestGeo()">
<div id="map_canvas" style="width:500px; height:450px; border:1px solid #666666; "></div>
</form>
</body>
</html>
I am getting output: Cannot locate user
What is the solution for this?
I have putted "html5_init.js" in my root directory of archive.
The correct validation is:
if (navigator.geolocation !== null)

How do I get all coords from a map?

Here is my google maps api project:
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var rio = new google.maps.LatLng(-22.894125,-43.199358);
var map;
function initialize() {
var myOptions = {
zoom: 10,
center: rio,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
google.maps.event.addListener(marker, 'click', toggleBounce);
}
function addMarkerAtCenter() {
var marker = new google.maps.Marker({
position: map.getCenter(),
draggable:true,
animation: google.maps.Animation.DROP,
map: map
});
}
function toggleBounce() {
if (marker.getAnimation() != null) {
marker.setAnimation(null);
} else {
marker.setAnimation(google.maps.Animation.BOUNCE);
}
}
</script>
</head>
<body onload="initialize()" style="margin:0px; padding:0px;">
<center><input type="button" value="Adicionar Marcador" onclick="addMarkerAtCenter()"/></center>
<center><div id="map_canvas" style="width:100%; height:100%"></div></center>
</body>
how can I, after adding multiple markers, get them and save into xml ?
thanks
I am pretty sure that it doesn't work that way. Markers know what map they belong to, but not the other way around. The way you would normally do this would be to have an Array, and each time you add a marker to your map you also add it to your array. Whenever you want to manipulate your markers you then run through that array and do the stuff that needs doing :)
What you are probably after (if you outputing stuff to XML) is just the coordinates of each marker added rather than the whole google marker object below is an example of how to get the coordinates and serialize them (badly) to XML.
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var rio = new google.maps.LatLng(-22.894125,-43.199358);
var map;
//you probably just want to store coordinates of markers
var coords = []
function initialize() {
var myOptions = {
zoom: 10,
center: rio,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
// google.maps.event.addListener(marker, 'click', toggleBounce);
}
function addMarkerAtCenter() {
var marker = new google.maps.Marker({
position: map.getCenter(),
draggable:true,
animation: google.maps.Animation.DROP,
map: map
});
//get the coordinates of the marker
pos = marker.getPosition();
//save the coordinates
coords.push({lat:pos.lat(), lng:pos.lng()})
}
function toggleBounce() {
if (marker.getAnimation() != null) {
marker.setAnimation(null);
} else {
marker.setAnimation(google.maps.Animation.BOUNCE);
}
}
//a primitive serialize function - add something more sophisticated
function serialize(arr) {
xml = "<markers>";
for (i=0;i<arr.length;i++) {
xml += "<marker>";
for(var prop in arr[i]) {
if(arr[i].hasOwnProperty(prop))
xml += "<" + prop +">" + arr[i][prop] + "</" + prop +">";
}
xml += "</marker>";
}
xml +="</markers>";
//do something with the result
alert(xml);
}
</script>
</head>
<body onload="initialize()" style="margin:0px; padding:0px;">
<center><input type="button" value="Adicionar Marcador" onclick="addMarkerAtCenter()"/> <input type=button onClick="javascript:serialize(coords)" value="To XML"></center>
<center><div id="map_canvas" style="width:100%; height:100%"></div></center>
</body>