Issue with google map API - google-maps

I have to translate a google map api code from v2 to v3. I've tried but it is not working.
This is the old version code:
function getQueryVariable(variable){
var query = window.location.search.substring(1);
var vars=query.split("&");
for(var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
}
var map = null;
var geocoder = null;
function showAddress(address, year1,year2,year3) {
map = new GMap2(document.getElementById("map_canvas"));
geocoder = new google.maps.Geocoder();
if (geocoder) {
geocoder.getLatLng(address,function(point) {
if (!point) {
alert(address + " not found");
} else {
map.setCenter(point, 11);
var marker = new GMarker(point);
map.addOverlay(marker);
}
}
);
}
}
This is what I wrote:
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(decodeURIComponent(pair[0]) {
return pair[1];
}
}
}
var map = null;
var geocoder = null;
function showAddress(address) {
var map=new google.maps.Map(document.getElementById("map_canvas"));
geocoder = new google.maps.Geocoder();
geocoder.geocode(address, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var center = results[0].geometry.location;
map.setCenter(center);
var marker = new google.maps.Marker({
map: map,
position: center
});
}
}
}
Someone can tell me what I'm doing wrong?
Thanks a lot.
Marcello

There are syntax errors in your code. But the main issue is you need to initialize the google.maps.Map object. Currently there are 3 required options in the google.maps.MapOptions object:
https://developers.google.com/maps/documentation/javascript/reference#MapOptions
center | LatLng | The initial Map center. Required.
mapTypeId | MapTypeId | The initial Map mapTypeId. Required.
zoom | number | The initial Map zoom level. Required.
This works for me:
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(decodeURIComponent(pair[0])) {
return pair[1];
}
}
}
var map = null;
var geocoder = null;
function showAddress(address) {
var map=new google.maps.Map(document.getElementById("map_canvas"),{center:new google.maps.LatLng(0,0), zoom:2, mapTypeId : google.maps.MapTypeId.ROADMAP});
geocoder = new google.maps.Geocoder();
geocoder.geocode({address:address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var center = results[0].geometry.location;
map.setCenter(center);
if (results[0].geometry.viewport) map.fitBounds(results[0].geometry.viewport)
else if (results[0].geometry.bounds) map.fitBounds(results[0].geometry.bounds)
var marker = new google.maps.Marker({
map: map,
position: center
});
} else alert("Geocoder returns: " + status);
});
}
working example

Related

Display multiple google map list

I am trying to display a list of agency with information such as phone, email etc...and for each a small google map with address. The address is dynamics and render through a loop in twig.
The problem is only the first map is render.
function initMap() {
var x = document.querySelectorAll('div[id^="map-"]');
for(var i = 1; i < x.length; ++i )
{
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(53.3496, -6.3263);
var mapOptions =
{
zoom: 16,
center: latlng
}
var stringAddress = '';
var stringAddress = $("#address-"+i).text();
map = new google.maps.Map(document.getElementById('map-'+ i), mapOptions);
codeAddress(stringAddress);//call the function
}
}
and my code function :
function codeAddress(address) {
geocoder.geocode( {address:address}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);//center the map over the result
//place a marker at the location
var marker = new google.maps.Marker(
{
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
I find the solution the loop was wrong.
instead of
for(var i = 1; i < x.length; ++i )
do
for(var i = 1; i <= x.length; ++i )

Google Maps Nearby Search (Show Selected nearby markers only with autocomplete )

I have this code, which works fine, but there is just one issue which I am getting:
When we search nearby places, it appends the new nearby search markers with the old markers, screenshots are attached in these links.
Here I have searched the nearby banks:
http://prntscr.com/aouxra
It has successfully shown, but now if I search another nearby place like hotel, it will append its markers with the banks markers which has been searched previously, like this:
http://prntscr.com/aouz23
I want to only show the markers of the autocompleted nearby search query only.
function getNearby(lat,lng,map){
var availableTags = [
"hotel",
"bank",
"atm",
"school",
];
$( "#nearby" ).autocomplete({
source: availableTags,
select: function (event, ui) {
var request = null;
request = {
location: {lat:lat, lng:lng},
radius: 5500,
types: [ui.item.value]
};
var service = null;
var infowindow = null;
infowindow = new google.maps.InfoWindow();
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
//var markers = [];
var markers = [];
var bounds = map.getBounds()
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++)
{
createMarker(results[i]);
//alert(results)
}
}
}
function createMarker(place) {
//markers.push(place);
var marker = '';
var placeLoc = '';
placeLoc = place.geometry.location;
marker = new google.maps.Marker({
map: map,
position: placeLoc
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
alert(markers.length);
}
});
}
function getLocation() {
$("#myNearby").css('display', 'block');
$("#directions").css('display', 'none');
$("#map").css('display', 'none');
$("#panel").css('display', 'none');
$("#load").css('display', 'none');
$("#googleMap").css('display', 'block');
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
alert("Geolocation is not supported by this browser.");
}
}
function showPosition(position) {
setLocationValue(position.coords.latitude,position.coords.longitude);
//getCurrentLocationValue(position.coords.latitude,position.coords.longitude);
var mapProp = {
center:new google.maps.LatLng(position.coords.latitude,position.coords.longitude),
zoom:10,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
var myMarker = new google.maps.Marker({
position: {lat:position.coords.latitude, lng:position.coords.longitude},
animation:google.maps.Animation.BOUNCE
});
myMarker.setMap(map);
var infowindow = new google.maps.InfoWindow({
content:"You are Located in Lat: "+position.coords.latitude+' Lng: '+position.coords.longitude
});
infowindow.open(map,myMarker);
getNearby(position.coords.latitude,position.coords.longitude,map);
<?php /*?>$("#myNearby a").click(function(){
//alert('Working');
var request = {
location: {lat:position.coords.latitude, lng:position.coords.longitude},
radius: 5500,
types: [$("#location").val()]
};
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);
});
}
});<?php */?>
}
function setLocationValue(lat,lng){
var latlng = new google.maps.LatLng(lat, lng);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({latLng: latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
var arrAddress = results;
//console.log(results);
$.each(arrAddress, function(i, address_component) {
if (address_component.types[0] == "locality") {
itemLocality = address_component.address_components[0].long_name;
//console.log("City: " + address_component.address_components[0].long_name + itemLocality);
$("#location").val(itemLocality);
}
});
}
else{
alert("No results found");
}
}
else {
alert("Geocoder failed due to: " + status);
}
});
}
Remove the existing markers from the map before showing the new ones. Make the markers array global, then do this at the beginning of getNearby:
for (var i=0; i<markers.length; i++) {
markers[i].setMap(null);
}
markers = [];

Can someone tell me why I can see an InfoWindow when I click on an map marker?

Here is my code that will pull data from mysql and display the markers on the map. But I cant get the info windows to show when I click on a marker. Thank for any help.
The reference to the infowindows is at the very bottom on the page close to the end of the code after the ajax reference.
Thanks
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
function LoadMarkers(encodedString)
{
var bounds = new google.maps.LatLngBounds();
var stringArray = [];
stringArray = encodedString.split("****");
var x;
for (x = 0; x < stringArray.length; x = x + 1)
{
var addressDetails = [];
var marker;
addressDetails = stringArray[x].split("&&&");
var lat = new google.maps.LatLng(addressDetails[1], addressDetails[2]);
var image = new google.maps.MarkerImage(addressDetails[3]);
var marker = new google.maps.Marker({
map: map,
icon: image,
position: lat,
content: addressDetails[0]
});
markersArray.push(marker);
google.maps.event.addListener( marker, 'click', function () {
closeInfos();
var info = new google.maps.InfoWindow({content: this.content});
info.open(map,this);
infos[0]=info;
});
bounds.extend(lat);
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(map);
}
}
}
map.fitBounds(bounds);
}
var geocoder;
var map;
var markersArray = [];
var infos = [];
geocoder = new google.maps.Geocoder();
var myOptions = {
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = null;//new google.maps.Map(document.getElementById("map_canvas"), myOptions);
jQuery(document).ready( function($){
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
LoadMarkers(document.getElementById("encodedString").value);
setInterval(function () {
jQuery.ajax({
url:'ajaxload.php',
type: "POST",
data: {'refreshed':true},
success: function(data)
{
LoadMarkers(data);
}
});
}, 10000);
//Manages the info windows
function closeInfos(){
if(infos.length > 0){
infos[0].set("marker",null);
infos[0].close();
infos.length = 0;
}
}
});
The function LoadMarkers is defined in global scope, but the function closeInfos is defined locally inside the $.ready-callback.
Because of that the call of closeInfos() inside the click-handler of the marker fails and stops the further execution of the click-handler.
You must make closeInfos global accessible:
window.closeInfos=function(){
if(infos.length > 0){
infos[0].set("marker",null);
infos[0].close();
infos.length = 0;
}
}

google api to search nearby address using their latitude,longitude from database

I need to retrieve a set of nearby addresses from google api using their latitude,longitude values.Latitude,longitude values are retrieved from a database.Is there a way to accomplish this?
Use Google Maps Javascript Api.
https://developers.google.com/maps/documentation/javascript/examples/geocoding-reverse
And Read a developer guide https://developers.google.com/maps/documentation/javascript/tutorial
Here is how it can be done with a combination of jquery and the google api. the $.getJSON call is invoking a service that gets a list of lat/lng objects in a pretty standard name and address kind of format and pushes everything into a marker array.
In this example the user enters an address in the "useradd" control, which becomes one blue marker, and some nearby things in the database are displayed as red markers.
I have found the map to be very sensitive to styling changes, especially modifying it's height and width, I am sure there is some way to deal with that, just have not found it yet.
<script type="text/javascript">
var geocoder;
var map;
var markersArray = [];
//---------------------------------------------------------------------------------------------------------------
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(0, 0); //add some real starting coords
var mapOptions = {
zoom: 12,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
$('#loadMsg').hide().ajaxStart(function () { $(this).show(); }).ajaxStop(function () { $(this).hide(); });
}
//---------------------------------------------------------------------------------------------------------------
function getStringfromJSON(invalue) {
if (!invalue) { return ''; } else { return invalue; }
}
function codeAddress() {
var address = document.getElementById("useradd").value;
if (address.length == 0) return;
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
geocoder.geocode
(
{ 'address': address },
function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var blueIcon = new google.maps.MarkerImage("http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png");
var marker = new google.maps.Marker({ map: map, position: results[0].geometry.location, icon: blueIcon, clickable: false });
marker.setTitle(address);
var lat = results[0].geometry.location.lat();
var lng = results[0].geometry.location.lng();
var dist = document.getElementById("selMiles").value;
var pageurl = '../Search/GetNearbys?lat=' + lat + '&lng=' + lng + '&dist=' + dist;
$.getJSON(pageurl,
function (data) {
for (var x = 0; x < data.length; x++) {
var facid = data[x].ID;
var facname = getStringfromJSON(data[x].Name);
var streetaddress = getStringfromJSON(data[x].StreetAddress);
var address2 = getStringfromJSON(data[x].Address2);
var city = getStringfromJSON(data[x].City);
var state = getStringfromJSON(data[x].State);
var zip = getStringfromJSON(data[x].ZipCode);
var xlat = data[x].Latitude;
var xlng = data[x].Longitude;
var xlatlng = new google.maps.LatLng(xlat, xlng);
var xmarker = new google.maps.Marker({ map: map, position: xlatlng, facilityid: facid });
xmarker.setTitle(facname + ' ' + streetaddress + ' ' + address2 + ' ' + city + ',' + state + ' ' + zip);
markersArray.push(xmarker);
google.maps.event.addListener(xmarker, 'click',
function () {
window.open('../Profile?id=' + this.facilityid, '_blank');
});
}
},
function (succeess) { }
);
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
markersArray.push(marker); //put it here so it gets reset after each search
}
);
}
</script>

Google Maps Elevation Service

I have this function which is invoked upon clicking a button. The function creates a marker at a predefined position. I then use the elevation service for the given point. When I click the button, the alert message (I've put it there for diagnostics) displays 'undefined', and then the marker appears (in fact the marker should appear before the alert box!). I've tried my best to identify the source of the problem but in vain. Can anyone help me please? Thanks.
function buttonClicked () {
addNode(someLat, someLong);
alert(getElev(markers[0]));
}
function addNode(lat, lng) {
var LatLng = new google.maps.LatLng(lat, lng);
var marker = new google.maps.Marker({
position: LatLng,
});
marker.setMap(map);
markers.push(marker);
}
function getElev (marker) {
var ht = 0;
var locations = [];
var clickedLocation = marker.getPosition();
locations.push(clickedLocation);
var positionalRequest = {
'locations': locations
}
elevator.getElevationForLocations(positionalRequest, function (results, status) {
if (status == google.maps.ElevationStatus.OK && results[0])
ht = results[0].elevation;
});
return ht;
}
Add the alert here and it should work. The function inside getElevationForLocations does not occur within getElev, but is called asynchronously. so ht is not set within getElev.
elevator.getElevationForLocations(positionalRequest, function (results, status) {
if (status == google.maps.ElevationStatus.OK && results[0]){
ht = results[0].elevation;
alert(ht);
}
});
altitude = 0; // Declared with out "var" make it superglobal
function buttonClicked () {
addNode(someLat, someLong);
alert(getAltitude());
}
function addNode(lat, lng) {
var LatLng = new google.maps.LatLng(lat, lng);
var marker = new google.maps.Marker({
position: LatLng,
});
marker.setMap(map);
markers.push(marker);
}
function getElev (marker) {
var locations = [];
var clickedLocation = marker.getPosition();
locations.push(clickedLocation);
var positionalRequest = {
'locations': locations
}
elevator.getElevationForLocations(positionalRequest, function (results, status) {
if (status == google.maps.ElevationStatus.OK && results[0])
setAltitude(results[0].elevation);
});
}
//getters and setters for altitude
function setAltitude(a){
altitude = a;
}
function getAltitude(){
return altitude;
}