Google maps API JS3 SSL - javascript

I have a website here : www.hosting6280514.az.pl/ that uses SSL ... I try to display google maps on that page, but only the controls, markers and map/satellite switch is displayed, the actual map isn't. This is the code I'm using:
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #map-canvas {
margin: 0;
padding: 0;
height: 100%;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var map;
function refreshing() {
setTimeout("location.reload(true);",5000);
}
function initialize()
{
var position = new google.maps.LatLng(<?php echo$lat; ?>,<?php echo$lgt; ?>);
var mapOptions =
{
zoom: 18,
center: position,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
/*var image = new google.maps.MarkerImage('http://hosting6280514.az.pl/pawel/images/car.png',
// This marker is 129 pixels wide by 42 pixels tall.
new google.maps.Size(129, 42),
// The origin for this image is 0,0.
new google.maps.Point(0,0),
// The anchor for this image is the base of the flagpole at 18,42.
new google.maps.Point(18, 42)
);*/
var marker = new google.maps.Marker(
{
position: position, // its position is where position variable points
title: "Car's position"
//icon: image
});
marker.setMap(map); // To add the marker to the map, call setMap();
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body onload="JavaScript:refreshing();">
<div id="map-canvas"></div>
</body>
</html>
Sorry, Question is: does anyone know why map is not displaying ?

In order to update the position on the map, try something along those lines.
You may also use geolocation.watchPosition if you would like to get the current position.
var position, marker;
function updateLocation() {
$.ajax({
url: '/something.php',
dataType: 'JSON',
success: function(data) {
position = new google.maps.LatLng(data.lat, data.lng);
marker.setPosition(position);
}
});
}
function initialize() {
position = // same as you have it
// ...
marker = // same as you have it
}

Related

How to add a new marker to map using flask_googlemaps?

I'm making a new app where the user can add the places that he visited on the map, am using flask_googlemaps extension to create the map from a view and i want to add a new marker on this map that get generated from the view .
The markers I've created them manually inside the view,
views.py
#mapapp.route('/gomap')
def gomap():
fullmap = Map(
identifier="fullmap",
varname="fullmap",
style=(
"height:100%;"
"width:100%;"
"top:0;"
"left:0;"
"position:absolute;"
"z-index:200;"
),
cluster=False,
lat=42.8770413,
lng=74.4517747,
markers=[
{
'icon': '//maps.google.com/mapfiles/ms/icons/green-dot.png',
'lat': 42.8770413,
'lng': 74.4513254,
'infobox': "Hello I am <b style='color:green;'>GREEN</b>!"
}
],
zoom="12"
)
return render_template('example_fullmap.html', fullmap=fullmap)
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Flask Google Maps Full Map Example</title>
<link rel="stylesheet" href="">
{{fullmap.js}}
</head>
<body>
<h1>Flask Google Maps Full Map Example</h1>
{{ fullmap.html }}
<script type="text/javascript">
var map;
function initialize() {
var myLatlng = new google.maps.LatLng(42.8770413,74.4517747);
var myOptions = {
zoom: 10,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
styles: [{"stylers": [{ "saturation": -100 }]}]
};
map = new google.maps.Map(document.getElementById("fullmap"), myOptions);
function placeMarker(location) {
var text = prompt("Комментарий");
var marker = new google.maps.Marker({
position: location,
map: map,
title: text,
icon: {
url: "http://www.suzuki.fr/media/image/interface/map-marker.png",
scaledSize: new google.maps.Size(42, 42)
}
});
}
}
google.maps.event.addDomListener(window, "load", initialize());
</script>
</body>
</html>
If you can see down where am creating a new marker if I clicked on the map, but if I clicked nothing happens, actually the function not calling it self, in the page source I can see my JavaScript codes but in action nothing happens.
You will need to execute the placeMarker() function. May be using self executing function is all you will need:
(function placeMarker(location) {
var text = prompt("Комментарий");
var marker = new google.maps.Marker({
position: location,
map: map,
title: text,
icon: {
url: "http://www.suzuki.fr/media/image/interface/map-marker.png",
scaledSize: new google.maps.Size(42, 42)
}
});
}());
Replace your placeMarker() functions with above self executing method. Make sure you pass proper location to the method.

Google Maps API: Want geolocation to click automatically on data layer below

I am trying to build a map-based site that identifies a user's geolocation, draws a marker at his/her position, and then uses that marker/location to click on a data layer (in this case, a GeoJSON layer). Essentially, the user's location should trigger an infowindow automatically if he or she is located on an area delineated by the geojson file. Ideally, each time the user changes location it will be clicking the map to check this GeoJSON layer for info.
So far, I can get the user's location successfully. The map centers on that location. And manual clicks on the GeoJSON layer also populate the info window correctly. But it's not clicking automatically when getting the user location.
I've seen lots of examples where a forced click on a marker takes place, but I can't seem to find one that clicks a data layer. Unfortunately I'm more of a GIS person assigned to a coding job on this, which is way out of my league, so I'm struggling to figure out where I'm going wrong with this.
Here's the script, perhaps I'm making a mistake here:
$<script type="text/javascript">
//centers the map on Iowa City
var map,
currentPositionMarker,
mapCenter = new google.maps.LatLng(41.661354, -91.534729),
map;
function initializeMap()
{
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 18,
center: mapCenter,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
map.data.loadGeoJson('test2.json');
map.data.setStyle({
strokeColor: '#2687bf',
strokeWeight: 5
});
map.data.addListener('click', function(event) {
document.getElementById('info-box').textContent =
event.feature.getProperty('description');
});
}
function locError(error) {
// the current position could not be located
alert("The current position could not be found!");
}
function setCurrentPosition(pos) {
currentPositionMarker = new google.maps.Marker({
map: map,
draggable: true,
position: new google.maps.LatLng(
pos.coords.latitude,
pos.coords.longitude
),
title: "Current Position"
});
new google.maps.event.trigger( 'test2.json', 'click' );
map.panTo(new google.maps.LatLng(
pos.coords.latitude,
pos.coords.longitude
));
}
function displayAndWatch(position) {
// set current position
setCurrentPosition(position);
// watch position
watchCurrentPosition();
}
function watchCurrentPosition() {
var positionTimer = navigator.geolocation.watchPosition(
function (position) {
setMarkerPosition(
currentPositionMarker,
position
);
});
}
function setMarkerPosition(marker, position) {
marker.setPosition(
new google.maps.LatLng(
position.coords.latitude,
position.coords.longitude)
);
}
function initLocationProcedure() {
initializeMap();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(displayAndWatch, locError);
} else {
alert("Your browser does not support the Geolocation API");
}
}
$(document).ready(function() {
initLocationProcedure();
});
</script>
</head>
<body>
<div id="map_canvas" style="height:600px;"></div>
<div id="info-box" style="height:250px;">INFO</div>
</body>
</html>
And here are links to my JSON and full HTML file for this:
https://sites.google.com/site/ecocritkml/coding
The JSON is obviously specific to Iowa City, Iowa, but it could be modified easily in a text editor. Any ideas would be really helpful here.
I think I got it.
I had to use a few tricks (some maybe a little dirty)
I put a 500ms delay with setTimeout; this could have been done more elegantly, no doubt
I make a temporary polygon, because it permits to use containsLocation()
I don't invoke a click, but there is a loop over the polygon features, I read the description there, and set it to the div
..
<!doctype html>
<html lang="en">
<head>
<title>Google maps</title>
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src=http://maps.google.com/maps/api/js?v=3&sensor=true&language=en"></script>
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map_canvas {
height: 100%;
}
#info-box {
background-color: white;
border: 1px solid black;
bottom: 30px;
height: 20px;
padding: 10px;
position: absolute;
left: 30px;
}
</style>
<script type="text/javascript">
//centers the map on Iowa City
var map,
currentPositionMarker,
mapCenter = new google.maps.LatLng(41.661354, -91.534729),
map;
function initializeMap() {
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 18,
center: mapCenter,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
map.data.loadGeoJson('test2.json');
map.data.setStyle({
strokeColor: '#2687bf',
strokeWeight: 5
});
map.data.addListener('click', function(event) {
document.getElementById('info-box').textContent = event.feature.getProperty('description');
});
}
function locError(error) {
// the current position could not be located
}
function setCurrentPosition(pos) {
currentPositionMarker = new google.maps.Marker({
map: map,
draggable: true,
position: new google.maps.LatLng(
pos.coords.latitude,
pos.coords.longitude
),
title: "Current Position"
});
// Wait half a second, then take a loop of the features, see if the marker is inside one of them
setTimeout(function() {
map.data.forEach(function(feature){
var figure = feature.getGeometry();
if(figure.getType() == 'Polygon') {
// make a temporary polygon, see if the marker is inside
var tempPolygon = new google.maps.Polygon({
paths: figure.getAt(0).getArray(), // #see http://stackoverflow.com/questions/33249127/using-containslocation-with-a-google-maps-data-polygon
map: null
});
if(google.maps.geometry.poly.containsLocation(currentPositionMarker.getPosition(), tempPolygon)) {
// marker is inside this feature
// invoke a click. well, just pretend ...
document.getElementById('info-box').textContent = feature.getProperty('description');
}
}
var b;
})
}, 500);
map.panTo(new google.maps.LatLng(
pos.coords.latitude,
pos.coords.longitude
));
}
function displayAndWatch(position) {
// set current position
setCurrentPosition(position);
// watch position
watchCurrentPosition();
}
function watchCurrentPosition() {
var positionTimer = navigator.geolocation.watchPosition(function (position) {
setMarkerPosition(
currentPositionMarker,
position
);
});
}
function setMarkerPosition(marker, position) {
marker.setPosition(
new google.maps.LatLng(
position.coords.latitude,
position.coords.longitude
)
);
// now we see if the marker is inside one of the polygons
var a = 0;
}
function initLocationProcedure() {
initializeMap();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(displayAndWatch, locError);
}
else {
// alert("Your browser does not support the Geolocation API");
}
}
$(document).ready(function() {
initLocationProcedure();
});
</script>
</head>
<body>
<div id="map_canvas" style="height:600px;"></div>
<div id="info-box" style="height:250px;">INFO</div>
</body>
</html>

Multiple Google Maps icons?

I'm trying to combine the following two blocks of codes together.
but for some reason, when i load the page in the browser, First the second blocks of code loads the marker on the map and then the page refreshes and the first blocks of code loads on the map!
This is my entire code:
<!DOCTYPE html>
<html>
<head>
<title>Google maps</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #map-canvas {
margin: 0;
padding: 0;
height: 100%;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var map;
geocoder = new google.maps.Geocoder();
function initialize() {
var mapOptions = {
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
codeAddress();
}
function codeAddress() {
var address = '<?= $_GET['location'] ?>';
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
icon: 'meicon.png',
map: map,
position: results[0].geometry.location
});
} else {
alert("Error loading map");
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
<script type="text/javascript">
var locations = [
['Bondi Beach', 51.5033631,-0.1276253, 1]
];
var maps = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 15,
center: new google.maps.LatLng(51.5033630,-0.1276250),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var markers, i;
for (i = 0; i < locations.length; i++) {
markers = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: maps
});
google.maps.event.addListener(markers, 'click', (function(markers, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, markers);
}
})(markers, i));
}
</script>
</body>
</html>
could someone please advise on this issue?
Thanks in advance.
It's probably because you're calling the geocoder on the address in the first block, which is an async call to google to check the address. While the code is talking to google the page runs the second code block. When that call returns it runs the rest of the code in the first block, which sets the center of the map.
The reason is simple you are loading two map the first called in <head> script what build a map in map-canvas named map. the second in body script you create another map named maps and this too create in map-canvas.You need only a working map and with this do what you nedd.

Google Map API marker update from JS

I would like to ask you a solution for this problem.
I have a JS with a variable inside that is updated overtime by a JAVA application (i.e. JAVA writer into a thread), after that I take the coordinates from that variable and I create a new object Marker for my google maps. The problem is that the marker does not changes position, it changes only if I refresh the whole page (I dont want to do this).
Here's the code to be more clear.
The inputData.js where the variable is written by the java application
var newMarker = {'latitude':38.25705300000004,'longitude': 140.83760400000006};
my html page used to display the map
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Simple markers</title>
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=MYKEY">
</script>
<script type="text/javascript" src="inputData.js"></script>
<script>
var map;
var sendai = new google.maps.LatLng(38.259535, 140.846816);
var lastPosition;
var image = 'images/circle-16.png';
function initialize() {
var mapOptions = {
zoom: 12,
center: sendai,
mapTypeId: google.maps.MapTypeId.ROADMAP};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
setInterval(refreshData, 2000);
function refreshData() {
var marker = new google.maps.Marker({
map: map,
icon: image,
draggable: false
});
marker.setPosition(new google.maps.LatLng(newMarker.latitude, newMarker.longitude));
map.setCenter(new google.maps.LatLng(newMarker.latitude, newMarker.longitude));
map.setZoom(18);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
If I open my page like this everything work but when I change the script "inputData.js" the marker does not changes position.
The method setCenter on the other hand seems to work properly.
Help me please!
You'll need to reload the updated script to get the updated position:
function initialize() {
var mapOptions = {
zoom: 18,
center: sendai,
mapTypeId: google.maps.MapTypeId.ROADMAP},
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions),
//we will store the LatLng here
pos = new google.maps.MVCObject(),
//use a single marker with updated position
marker = new google.maps.Marker();
//set the latLng of the MVCObject
pos.set('latLng',new google.maps.LatLng(newMarker.latitude,
newMarker.longitude));
//bind the markers position to the latLng of the MVCObject
marker.bindTo('position',pos,'latLng');
marker.setMap(map);
setInterval(function(){
//the currently loaded script
var script=document.querySelector('script[src^="inputData.js"]'),
//the updated script
update=document.createElement('script');
//load-handler for the updated script
google.maps.event.addDomListenerOnce(update,'load',function(){
pos.set('latLng',new google.maps.LatLng(newMarker.latitude,
newMarker.longitude));
map.setCenter(pos.get('latLng'));
map.setZoom(18);
});
//replace current script with updated script
script.parentNode.replaceChild(update,script);
//load update
update.src='inputData.js?'+new Date().getTime();
},2000);
}
You don't need to create new instance of marker every time. Update your code with this and try:
var map;
var sendai = new google.maps.LatLng(38.259535, 140.846816);
var lastPosition;
var image = 'images/circle-16.png';
function initialize() {
var mapOptions = {
zoom: 12,
center: sendai,
mapTypeId: google.maps.MapTypeId.ROADMAP};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
var marker;
marker = new google.maps.Marker({
map: map,
icon: image,
draggable: false
});
marker.setPosition(new google.maps.LatLng(newMarker.latitude, newMarker.longitude));
map.setCenter(new google.maps.LatLng(newMarker.latitude, newMarker.longitude));
map.setZoom(18);
setInterval(refreshData, 2000);
function refreshData() {
marker.setPosition(new google.maps.LatLng(newMarker.latitude, newMarker.longitude));
map.setCenter(new google.maps.LatLng(newMarker.latitude, newMarker.longitude));
map.setZoom(18);
}
google.maps.event.addDomListener(window, 'load', initialize);

Google maps grey background when created with jQuery each()?

I was trying to simplify the way I add Google maps to my pages.
I'm using this markup for each map:
<div class="map" data-coordinates="-34.397, 150.644">
<div class="canvas" id="map_canvas"></div>
</div>
and this jquery code:
jQuery(function($) {
var maps = $('.map');
maps.each(function() {
var $this = $(this),
mapId = $this.find('.canvas').attr('id'),
coordinates= $this.data('coordinates');
// set map options
var mapOptions = {
center: new google.maps.LatLng(coordinates),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// create the map
var map = new google.maps.Map(document.getElementById(mapId), mapOptions);
});
});
this is a recreation of the tutorial on the google maps website.
when I do it like the tutorial it works fine, but when I use my code above I get the map controls with a grey background, I also tried jQuery(window).load(); with the same result, and the issue seems to be from each() because when I create the map without it, it works fine.
this is the code that works:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
</style>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&sensor=SET_TO_TRUE_OR_FALSE">
</script>
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>
There's a problem with coordonates.
google.maps.LatLng() accepts Lat and Lng as separate params, not a composite string.
Try :
jQuery(function($) {
$('.map').each(function() {
var $this = $(this),
canvas = $this.find('.canvas').get(0),
coordinates = $this.data('coordinates').split(/,\s?/);
// set map options
var mapOptions = {
center: new google.maps.LatLng(Number(coordinates[0]), Number(coordinates[1])),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// create the map
var map = new google.maps.Map(canvas, mapOptions);
});
});
You might need to test that regexp.

Categories

Resources