Creating several google maps marker based on address - api

I am trying to place google map markers based on several address, i have manage to show them based on coordinates, but i dont have coordinates i only have address. Here is my code what i have for now
<div id="map_canvas"></div>
var map;
function initialize() {
var styles = [{"featureType":"administrative","elementType":"all","stylers":[{"visibility":"simplified"}]},{"featureType":"landscape","elementType":"geometry","stylers":[{"visibility":"simplified"},{"color":"#fcfcfc"}]},{"featureType":"poi","elementType":"geometry","stylers":[{"visibility":"simplified"},{"color":"#fcfcfc"}]},{"featureType":"road.highway","elementType":"geometry","stylers":[{"visibility":"simplified"},{"color":"#dddddd"}]},{"featureType":"road.arterial","elementType":"geometry","stylers":[{"visibility":"simplified"},{"color":"#dddddd"}]},{"featureType":"road.local","elementType":"geometry","stylers":[{"visibility":"simplified"},{"color":"#eeeeee"}]},{"featureType":"water","elementType":"geometry","stylers":[{"visibility":"simplified"},{"color":"#dddddd"}]}];
var styledMap = new google.maps.StyledMapType(styles,
{name: "Styled Map"});
// the position of the marker
var zurichCenter = new google.maps.LatLng(47.3768866,8.541694);
var latlng = new google.maps.LatLng(47.4469659,8.5833443);
var latlng1 = new google.maps.LatLng(46.818188,8.227512);
var myOptions = {
zoom: 11,
center: zurichCenter,
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'map_style']
}
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker = new google.maps.Marker({
map: map,
position: latlng,
icon: 'img/pin-default.png' // location of the pin image, depending of the skin used
});
var marker1 = new google.maps.Marker({
map: map,
position: latlng1,
icon: 'img/pin-default.png' // location of the pin image, depending of the skin used
});
map.mapTypes.set('map_style', styledMap);
map.setMapTypeId('map_style');
}
google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addDomListener(window, "resize", function() {
var center = map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
});

Using the Geocoding API, as said in the comments, you can convert your address to coordinates.
You can find an example on how to use the API here.
I can't find an address in your code.
EDIT:
Here is a simple example (copied from the link above):
var geocoder = new google.maps.Geocoder();
var address = "Bergmannstraße 2, Berlin, Germany";
geocoder.geocode({'address': address}, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
resultsMap.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: resultsMap,
position: results[0].geometry.location
});
}
else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
Working fiddles:
http://jsfiddle.net/4mtyu/1167/
http://jsfiddle.net/4mtyu/1164/

Related

Google map API route from current location to marker

Working with the Google map API and routes or directions. I would like it such that when a user clicks a marker the route from the user's current location to that marker would render.
I have been studying the Google maps API documentation direction services example here.
Here is my attempt at adapting that. To me it seems this should work, so what am I missing? The route or direction between the user's current location and the marker is not rendering.
<!DOCTYPE html>
<html>
<body>
<h1>My First Google Map</h1>
<div id="googleMap" style="width:60%;height:800px;"></div>
<script>
var myLatLng;
function geoSuccess(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer;
myLatLng = {
lat: latitude,
lng: longitude
};
var mapProp = {
// center: new google.maps.LatLng(latitude, longitude), // puts your current location at the centre of the map,
zoom: 15,
mapTypeId: 'roadmap',
};
var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer;
//call renderer to display directions
directionsDisplay.setMap(map);
var bounds = new google.maps.LatLngBounds();
// var mapOptions = {
// mapTypeId: 'roadmap'
// };
// Multiple Markers
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'My location'
});
var markers = [
['Ragazzi', 53.201472, -6.111626],
['McDonalds', 53.200482, -6.111337],
['my location', latitude, longitude]
];
// Info Window Content
var infoWindowContent = [
['<div>' +
'<h3>Ragazzi</h3>' +
'<p>Cafe eatin place.</p>' + ' <button onclick="calculateAndDisplayRoute(marker, i)"> Get Directions</button>' + '</div>'
],
['<div class="info_content">' +
'<h3>McDonalds</h3>' +
'<p>Excellent food establishment, NOT!.</p>' + '<button onclick="calculateAndDisplayRoute(marker, i)"> Get Directions</button>' +
'</div>'
]
];
// Display multiple markers on a map
var infoWindow = new google.maps.InfoWindow(),
marker, i;
// Loop through our array of markers & place each one on the map
for (i = 0; i < markers.length; i++) {
var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
title: markers[i][0]
});
// Allow each marker to have an info window
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infoWindow.setContent(infoWindowContent[i][0]);
infoWindow.open(map, marker);
}
})(marker, i));
marker.addListener('click', function() {
directionsService.route({
// origin: document.getElementById('start').value,
origin: myLatLng,
destination: marker.getPosition(),
travelMode: 'DRIVING'
}, function(response, status) {
if (status === 'OK') {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
});
// Automatically center the map fitting all markers on the screen
map.fitBounds(bounds);
}
}
// function calculateAndDisplayRoute(directionsService, directionsDisplay) {
// directionsService.route({
// // origin: document.getElementById('start').value,
// origin: myLatLng,
// destination: marker.getPosition(),
// travelMode: 'DRIVING'
// }, function(response, status) {
// if (status === 'OK') {
// console.log('all good');
// directionsDisplay.setDirections(response);
// } else {
// window.alert('Directions request failed due to ' + status);
// }
// });
// }
function geoError() {
alert("Geocoder failed.");
}
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(geoSuccess, geoError);
// alert("Geolocation is supported by this browser.");
} else {
alert("Geolocation is not supported by this browser.");
}
}
</script>
<script async src="https://maps.googleapis.com/maps/api/js?key=api key here"></script>
</body>
</html>
Thanks,
I have solved this. The problem was the line,
destination: marker.getPosition(),
was not correct. This was giving me the coordinates of my current location and not the marker clicked.
I set the latit and longit in the function that sets the infoWindow, which have been defined as a global variable,
// Allow each marker to have an info window
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infoWindow.setContent(infoWindowContent[i][0]);
infoWindow.open(map, marker);
latit = marker.getPosition().lat();
longit = marker.getPosition().lng();
// console.log("lat: " + latit);
// console.log("lng: " + longit);
}
})(marker, i));
Then these are set to the destination,
marker.addListener('click', function() {
directionsService.route({
// origin: document.getElementById('start').value,
origin: myLatLng,
// destination: marker.getPosition(),
destination: {
lat: latit,
lng: longit
},
travelMode: 'DRIVING'
}, function(response, status) {
if (status === 'OK') {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
});
The full code is here on github.
A gh-pages working example.

Google Maps API - Map not showing on second initialize

I have a page setup that requires multiple instances of Google Maps via the API to be initialized. All works fine when one map is initialized the first time. When you re click on the button to do so, the map does not fully show.
var locations = [
['test1', 45.440188, -75.676309, 1, 'transportation.png'],
['test2', 45.439463, -75.675751, 1, 'medical.png'],
['test3', 45.439792, -75.683544, 1, 'schools.png'],
['test4', 45.439652, -75.676929, 1, 'shopping.png']
];
function initialize_1() {
var mapOptions = {
center: new google.maps.LatLng(45.438612, -75.677561),
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas_1"), mapOptions);
marker = new google.maps.Marker({
position: new google.maps.LatLng(45.438612, -75.677561),
map: map
});
var marker, i;
var iconBase = 'http://www.elkproperty.com/new/images/icons/';
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
,icon: iconBase + locations[i][4]
});
}
}
I think the issue is that you are initialising map to a hidden layer. Try to move call to initialize_1() after show():
onclick="$('#units_1').hide(); $('#unitArrow_1').hide(); $('#amenity_1').show(); $('#amenityArrow_1').show(); initialize_1();"
Other option is to force resize event after divs are visible. For this to work you would probably have to make map variable global.
google.maps.event.trigger(map, 'resize');
Maybe unrelated to your question but do you have to initialise the map layer each time you show div with map? Maybe you could test whether it is initialised or not, for example:
var isInit_1 = false;
function initialize_1() {
if (isInit_1) { return; }
isInit_1 = true;
var mapOptions = {
...

Google Places API - Getting Phone Number and Website

I believe I need to make follow up calls to get the results I am looking for. However, I cannot get the phone number and www url for any of the results I pull up.
I am a novice and need some help explaining where in this code I can get the correct results pulled. Please see the demo site here:
http://news.yeselectric.com/gmaps-excel-master/
Here is my JS code:
var store = (function () {
var searchBox,
infowindow,
markers = [],
myLatlng = new google.maps.LatLng(50.0019, 10.1419),
myOptions = { zoom: 6, center: myLatlng, mapTypeId: google.maps.MapTypeId.ROADMAP, mapTypeControl: false, streetViewControl:false },
customIcons = { iconblue: './icons/blue.png' };
var init = function() {
map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
input = (document.getElementById('pac-input'));
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
searchBox = new google.maps.places.SearchBox((input));
store.listener();
},
listener = function() {
google.maps.event.addListener(searchBox, 'places_changed', function() {
//search for places
var places = searchBox.getPlaces();
for (var i = 0, marker; marker = markers[i]; i++) {
marker.setMap(null);
}
//set markers zero
markers = [];
$('.addaddress').empty();
//get new bounds
var bounds = new google.maps.LatLngBounds();
for (var i = 0, place; place = places[i]; i++) {
store.create_marker(place);
//append to the table
$('.addaddress').append('<tr><td>'+ place.name +'</td><td>'+ place.formatted_address +'</td><td>'+ place.formatted_phone_number +'</td><td>'+ place.website +'</td></tr>');
bounds.extend(place.geometry.location);
}
//set the map
map.fitBounds(bounds);
});
},
create_marker = function(info) {
//create a marker for each place
var marker = new google.maps.Marker({ map: map, icon: customIcons.iconblue, title: info.name, position: info.geometry.location });
//infowindow setup
google.maps.event.addListener(marker, "click", function() {
if (infowindow) {
infowindow.close();
}
infowindow = new google.maps.InfoWindow({content: info.name});
infowindow.open(map, marker);
});
//push the marker
markers.push(marker);
}
return {
init: init,
listener: listener,
create_marker: create_marker
};
})();
google.maps.event.addDomListener(window, 'load', store.init);
Google's API returns different place metadata, depending on which call you're using. To get more place details, you'll need to get the place's placeId and use that to make a call to place.getDetails()
Here's a more thorough answer: https://stackoverflow.com/a/9523345/2141296

Google maps API geolocation + radar places search

I am trying to use both Geolocation and Places from the google maps API to display a map (at my location) with the nearest places around me. The two examples work seperately but not together.
Can anyone tell me why there is a problem with this? am I overwriting the map with another or doing something else wrong?
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?v=3.exp&key=AIzaSyA93l5zPyIvGB7oYGqzLSk28r5XuIs2Do8
&sensor=true&libraries=places"></script>
<script>
var map;
var service;
var marker;
var pos;
function initialize() {
var mapOptions = {
zoom: 15
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Located'
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
var request = {
location:pos,
radius:500,
types: ['store']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request,callback);
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);
});
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
EDIT
Moved the code now so it looks like - Has not fixed the problem of location being undefined.
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var request = {
location:pos,
radius:500,
types: ['store']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request,callback);
pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Located'
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});'
Because of async call to navigator.geolocation.getCurrentPosition() which returns immediately, location property of request is undefined. Call to
service.nearbySearch(request,callback);
complains that location is missing. And that is true because pos is not set at that moment.
You have to move this part of code:
var request = {
location:pos,
radius:500,
types: ['store']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request,callback);
to
navigator.geolocation.getCurrentPosition(function(position) {
...
map.setCenter(pos);
and make variable infoWindow global.
This is changed initialize() function:
var map;
var service;
var marker;
var pos;
var infowindow;
function initialize() {
var mapOptions = {
zoom: 15
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
console.log(map);
// Try 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: 'Located'
});
map.setCenter(pos);
var request = {
location:pos,
radius:500,
types: ['store']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request,callback);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
console.log('after / to createMarker');
createMarker(results[i]);
}
}
}
}

marker clusterer doesn't cluster when zoom

i'm trying to learn google api and i want to use marker clusterer. i create a database
from here and do whatever google said. my code is
`
<script src="markerclusterer.js" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
var customIcons = {
restaurant: {
icon: 'images/pin1.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
bar: {
icon: 'images/pin2.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
}
};
function initialize() {
var markers = null;
var mcmarkers = [];
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(47.6145, -122.3418),
zoom: 12,
mapTypeId: 'satellite'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("phpsqlajax_genxml.php", function(data) {
var xml = data.responseXML;
markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"))
var point = new google.maps.LatLng(lat, lng);
var html = "<b>" + name + "</b> <br/>" + address;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
mcmarkers.push(marker);
var mc = new MarkerClusterer(map, mcmarkers);
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
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('POST', url, true);
request.send(null);
}
function doNothing() {}
//]]>
google.maps.event.addDomListener(window, 'load', initialize);
`
it works well when i open for the first time but when i zoom in or out there was no clusters except max zoom out. i couldn't figure it out. thanks for your help...
var mc = new MarkerClusterer(map, mcmarkers);
This line cannot be placed inside the for loop. but outside after it. I did exactly the same mistake:).