Center Google Maps InfoWindow On Load - javascript

I'm having a problem centering my InfoWindow on page load. On load, the map is centering on the marker, which puts the InfoWindow off screen (I'm working with a short height for my map container).
Now clicking the marker does re-center the map on the InfoWindow so that it looks exactly like I want. That being the case, I've even tried firing the marker.click trigger to achieve a solution on load, but had no luck. What am I missing?
JSFIDDLE: http://jsfiddle.net/q9NTS/7/
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script type="text/javascript">
var geocoder = new google.maps.Geocoder();
var marker;
var infoWindow;
var map;
function initialize() {
var mapOptions = {
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
setLocation();
}
function setLocation() {
var address = '#(Model.Event.Address)' + ', ' + '#(Model.Event.City)' + ', ' + '#(Model.Event.State)' + ' ' + '#(Model.Event.Zip)';
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var position = results[0].geometry.location;
marker = new google.maps.Marker({
map: map,
position: position,
title: '#(Model.Event.Venue)'
});
map.setCenter(marker.getPosition());
var content = 'blah';
infoWindow = new google.maps.InfoWindow({
content: content
});
google.maps.event.addListener(marker, 'click', function () {
infoWindow.open(map, marker);
});
//infoWindow.open(map, marker); doesn't work
google.maps.event.trigger(marker, 'click'); //still doesn't work
}
else {
//
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>

You apparently just need to wait longer before triggering the click event.
// wait until the map is idle.
google.maps.event.addListenerOnce(map, 'idle', function() {
setTimeout(function() {
// wait some more (...)
google.maps.event.trigger(marker, 'click'); //still doesn't work
},2000);
});
fiddle

Related

Google Map, Users Create Markers, How do I save

I've got code to allow users to pin a marker on a map. What I am missing is how to save the markers so that when the map reloads, the markers are still there.
<script src="http://maps.googleapis.com/maps/api/js"></script>
<script>
var map;
var myCenter=new google.maps.LatLng(38.9047,-77.0164);
function initialize()
{
var mapProp = {
center:myCenter,
zoom:7,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("googleMap"),mapProp);
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
}
function placeMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map,
});
var infowindow = new google.maps.InfoWindow({
content: 'Latitude: ' + location.lat() + '<br>Longitude: ' + location.lng()
});
infowindow.open(map,marker);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
You could utilize google.maps.Data API for that purpose, the example below demonstrates how to save and load markers info via localStorage.
function placeMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map,
});
var infowindow = new google.maps.InfoWindow({
content: 'Latitude: ' + location.lat() + '<br>Longitude: ' + location.lng()
});
infowindow.open(map, marker);
//place marker info
map.data.add(new google.maps.Data.Feature({properties:{},geometry:new google.maps.Data.Point(location)}));
}
function saveMarker() {
map.data.toGeoJson(function (json) {
localStorage.setItem('geoData', JSON.stringify(json));
});
}
function clearMarkers() {
map.data.forEach(function (f) {
map.data.remove(f);
});
}
function loadMarkers(map) {
var data = JSON.parse(localStorage.getItem('geoData'));
map.data.addGeoJson(data);
}
Demo

Geocoder is automatically panning google map to the left

I am creating a page with a marker that stays fixed at the center of a map, even if the user pans/zoom the map. When the user clicks on the marker it shows the full address of the marker.
The problem is that the infoWindow.setContent() shows a string when I supply one, but pans the map to the left (and doesnt show the infoWindow) when I supply results[0].formatted_address.
The code below is the reverse geocoding I have. The alert function (which I have uncommented) shows the address correctly.
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'latLng': input}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
//alert(results[0].formatted_address);
infoWindow.setContent(results[0].formatted_address);
infoWindow.open(map,marker);
} else {
alert('No results found');
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
And my complete Javascript Code is:
var map;
var marker;
var infoWindow = new google.maps.InfoWindow();
function initialize() {
function setUpMap(){
var mapOptions = {
zoom: 14,
center: new google.maps.LatLng(22.519422, 88.35741400000006),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),mapOptions);
google.maps.event.addListener(map, 'center_changed', function() {
removeMarker();
});
google.maps.event.addListener(map, 'idle', function() {
setMarker();
});
}
function removeMarker(){
marker.setMap(null);
}
function setMarker(){
marker = new google.maps.Marker({
position: map.getCenter(),
map: map,
title:"Hello World!"
});
google.maps.event.addListener(marker, 'click', function() {
var input = marker.getPosition();
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'latLng': input}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
//alert(results[0].formatted_address);
infoWindow.setContent(results[0].formatted_address);
infoWindow.open(map,marker);
} else {
alert('No results found');
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
});
}
setUpMap();
}
google.maps.event.addDomListener(window, 'load', initialize);
I think the problem is that, when the user clicks on the marker, somehow setMarker() gets called. I can't really find out where the problem is coming from. Can anyone help me find it?
It's forced by a interaction between the center_changed-handler and the autoPan of the infoWindow.
When you open a infoWindow the API by default tries to pan the map to be able to show the infoWindow at the best position. But when this happens the center of the map changes, the marker will be removed(that's why you don't see the infowindow). You must set the disableAutoPan-option of the infoWindow to true.
Modified code:
function initialize() {
function setUpMap() {
var mapOptions = {
zoom: 14,
center: new google.maps.LatLng(22.519422, 88.35741400000006),
mapTypeId: google.maps.MapTypeId.ROADMAP
},
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions),
infoWindow = new google.maps.InfoWindow({
disableAutoPan: true
}),
marker = setMarker(map, infoWindow);
google.maps.event.addListener(map, 'center_changed', function() {
infoWindow.close();
marker.setPosition(this.getCenter());
});
}
function setMarker(map, infoWindow) {
var marker = new google.maps.Marker({
position: map.getCenter(),
map: map,
title: "Hello World!"
});
google.maps.event.addListener(marker, 'click', function() {
var input = marker.getPosition();
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'latLng': input
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results)
if (results[0]) {
console.log(results[0].formatted_address)
//alert(results[0].formatted_address);
infoWindow.setOptions({
content: '<div style="xwidth:200px">' + results[0].formatted_address + '</div>'
});
infoWindow.open(map, marker);
} else {
alert('No results found');
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
});
return marker;
}
setUpMap();
}
google.maps.event.addDomListener(window, 'load', initialize);
html {
height: 100%
}
body {
height: 100%;
margin: 0;
padding: 0
}
#map_canvas {
height: 100%
}
<script src="https://maps.googleapis.com/maps/api/js?v=3"></script>
<div id="map_canvas"></div>

using google map geocoder.geocode before initializing the map

I have created a nice Google map form that gets clients data from the database ( with a jQuery post call to php) and loads it into the clients_details. if clients_details[]['location'] which is Latlng is provided in the database all works well and marker gets displayed as expected. Problem is that when clients_details[]['location'] is not provided then I use the address from clients_details[]['address'] and try to get position of the marker by using geocoder.geocode. However surprisingly every time the code gets to the geocoder it jumps from it and comes back to it after it initialized the map ! so markers wont get added to the map !
I am assuming it has something to do with JavaScript function priorities but not sure how
<script>
var clients_details // getting this from database;
var infowindow =[];
var geocoder;
var map;
function showMarkers(clients_details)
{
var marker = [];
for (var i = 0; i < clients_details.length; i++)
{
content = 'Test Content' ;
infowindow[i] = new google.maps.InfoWindow({
content: content,
maxWidth: 350
});
var client_location;
if (clients_details[i]['location'] !== null)
{
// Geting Lat and Lng from the database string
LatLng = clients_details[i]['location'];
client_location = new google.maps.LatLng (LatLng);
}
else
{
client_address = clients_details[i]['address'];
geocoder.geocode(
{ 'address': client_address},
function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
client_location = results[0].geometry.location;
}
else
alert('Geocode was not successful for the following\n\
reason: ' + clients_details[i]['name']+'\n' + status);
});
}
marker[i] = new google.maps.Marker({
position: client_location,
map: map,
title: clients_details[i]['name']
});
// Add 'click' event listener to the marker
addListenerMarkerList(infowindow[i], map, marker[i]);
}// for
}// function
The
marker[i] = new google.maps.Marker({
position: client_location,
map: map,
title: clients_details[i]['name']
});
Code should be inside the callback in the geocoder.geocode call.
Because in your code the client_location is computed after the marker[i].
What you could do is:
compute the client_location and when the client_locolation is computed
then compute the marker[i]
So your code could be like this:
// ... your code as is
geocoder.geocode(
{ 'address': client_address},
function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
client_location = results[0].geometry.location;
// closure needed, for the marker[i] to work correctly,
// because we are in a loop on i
(function (i) {
marker[i] = new google.maps.Marker({
position: client_location,
map: map,
title: clients_details[i]['name']
});
})(i);
}
else
{
alert('Geocode was not successful for the following\n\
reason: ' + clients_details[i]['name']+'\n' + status);
}
}
);
// .... your code as is
You need to bind your call back function to the right event. Bind the initialize of the map to window load. Inside that function then call the rest of the marker/geocoder logic. As extracted from their documentation:
function initialize() {
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(-25.363882, 131.044922)
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var marker = new google.maps.Marker({
position: map.getCenter(),
map: map,
title: 'Click to zoom'
});
google.maps.event.addListener(map, 'center_changed', function() {
// 3 seconds after the center of the map has changed, pan back to the
// marker.
window.setTimeout(function() {
map.panTo(marker.getPosition());
}, 3000);
});
google.maps.event.addListener(marker, 'click', function() {
map.setZoom(8);
map.setCenter(marker.getPosition());
});
}
google.maps.event.addDomListener(window, 'load', initialize);

Instagram pictures to Google Maps in a radius of 1km around you

I'm wondering if it's possible to get Instagram photo's to Google Maps working with API's. So far I got Google Maps working and it's showing my current location, along with a radius of 1km around me.
The thing I want to do is show a certain amount of Instagram pictures in that radius around me, taken by everybody.
But so far, I got no idea where or how to start, and if it's even possible.
The code for my google maps is:
</script>
<script type="text/javascript">
var map;
var service;
var marker;
var pos;
var infowindow;
function initialize() {
var mapOptions = {
zoom: 14
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
//HTML5 geolocation
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'This is your current position!'
});
var circle = new google.maps.Circle({
map: map,
position: pos,
radius: 1000, // 1km in metres
fillColor: '#6D86D1'
});
circle.bindTo('center', infowindow, 'position');
map.setCenter(pos);
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
},
function () {
handleNoGeolocation(true);
});
} else {
handleNoGeolocation(false);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
You have to use the media/search API to get photos around a location (lat/lng) and distance:
https://api.instagram.com/v1/media/search?lat=48.858844&lng=2.294351&distance=1000&access_token=ACCESS-TOKEN
Here is an implementation of getting instagram photos around any radius on google maps:
http://www.gramfeed.com/instagram/map

How can I display the address of my geocode in an info window? Google maps API

I am using geolocation to get the address of places on my google maps API by looking up the longitude and latitude and returning the results to my page for use in my database.
I have been unable to display these results in my infowindow in my map.
How can I using the code below include the address in my infowindow. It currently displays the long and lat with the following code:
infowindow.setContent('<div><strong>' + marker.getPosition()+ '</strong><br>');
infowindow.open(map, marker);
The function geocodePosition looks up the address of the coordinates and appends it to the html input in my form.
How can I adapt it to update the infowindow too. I have tried many methods now and no success. Any ideas??
<script type="text/javascript">
var geocoder = new google.maps.Geocoder();
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.');
}
});
}
function updateMarkerStatus(str) {
document.getElementById('markerStatus').value = str;
}
function updateMarkerPosition(latLng) {
document.getElementById('info').value = [
latLng.lat(),
latLng.lng()
].join(', ');
}
function updateMarkerAddress(str) {
document.getElementById('address').value = str;
}
function initialize() {
var latLng = new google.maps.LatLng(-34.397, 150.644);
var map = new google.maps.Map(document.getElementById('mapCanvas'), {
zoom: 8,
center: latLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: latLng,
title: 'Property location marker',
map: map,
draggable: true
});
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input);
var infowindow = new google.maps.InfoWindow();
autocomplete.bindTo('bounds', map);
google.maps.event.addListener(autocomplete, 'place_changed', function() {
var place = autocomplete.getPlace();
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17);
}
var image = new google.maps.MarkerImage(
place.icon, new google.maps.Size(71, 71),
new google.maps.Point(0, 0), new google.maps.Point(17, 34),
new google.maps.Size(35, 35));
marker.setIcon(image);
marker.setPosition(place.geometry.location);
infowindow.setContent('<div><strong>' + marker.getPosition()+ '</strong><br>');
infowindow.open(map, marker);
});
// Update current position info.
updateMarkerPosition(latLng);
geocodePosition(latLng);
infowindow.setContent('<div><strong>' + marker.getPosition()+ '</strong><br>');
infowindow.open(map, marker);
// Add dragging event listeners.
google.maps.event.addListener(marker, 'dragstart', function() {
updateMarkerAddress('Dragging...');
});
google.maps.event.addListener(marker, 'drag', function() {
updateMarkerStatus('Dragging...');
updateMarkerPosition(marker.getPosition());
});
google.maps.event.addListener(marker, 'dragend', function() {
updateMarkerStatus('Drag ended');
geocodePosition(marker.getPosition());
//Show property address in window
infowindow.setContent('<div><strong>' + marker.getPosition()+ '</strong><br>');
infowindow.open(map, marker);
});
}
// Onload handler to fire off the app.
google.maps.event.addDomListener(window, 'load', initialize);
</script>
marker.getPosition() is not going to provide the street address. Given your current code, your best bet is to move:
infowindow.setContent('<div><strong>' + marker.getPosition()+ '</strong><br>');
to your geocodePosition() function, and then to pass the infowindow object as a second argument to that function.
So in your initialize() function you would modify calls to geocodePosition by including a second argument:
function initialize() {
...
geocodePosition(marker.getPosition(), infowindow);
}
Then in your geocodePosition() function, you would accept the second argument, and update it with the responses[0].formatted_address value. I added variables to make it easier to pass on the values for address and the message.
function geocodePosition(pos, infowindow) {
geocoder.geocode({
latLng: pos
}, function(responses) {
if (responses && responses.length > 0) {
var address = responses[0].formatted_address;
updateMarkerAddress(address);
infowindow.setContent('<div><strong>' + address + '</strong><br>');
} else {
var msg = 'Cannot determine address at this location.';
updateMarkerAddress(msg);
infowindow.setContent('<div><strong>' + msg + '</strong><br>');
}
});
}
You might want to use Google map api - http://code.google.com/apis/maps/documentation/geocoding/#GeocodingRequests
There are others APIs that will give you the same - but most of them will cost money and with Google you get a lot of 'miles' for free.

Categories

Resources