I'm trying to get the autocomplete to work on a simple input text box. I have it working for one text box, but I have a second (to and from location) which it is throwing errors.
My code isn't very streamlined I don't think and I'm wondering if there is a cleaner method to get this working. I think my repetitive code maybe part of the problem. The 'to' input box doesn't work and no errors are thrown.
<script type="text/javascript">
$(document).on("pageinit", "#map_page", function () {
initialize();
layersOFFonload();
});
$(document).on('click', '#getDirectionsSubmit', function (e) {
e.preventDefault();
calculateRoute();
});
$(document).on('click', '#getCurrentLoc', function (e) {
e.preventDefault();
findCurrentPosition();
});
var directionDisplay,
directionsService = new google.maps.DirectionsService(),
map;
var geocoder = new google.maps.Geocoder();
var transitRoutesLayerKML = [];
var placeSearch, autocomplete;
function initialize() {
// set the default center of the map
var mapCenter = new google.maps.LatLng(55.1669513, -118.8031093);
// set route options (draggable means you can alter/drag the route in the map)
var rendererOptions = { draggable: true };
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
//updateMapSize(mapCenter);
// set the display options for the map
var myOptions = {
mapTypeControl: false,
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: mapCenter
}
// add the map to the map placeholder
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
// bind the map to the directions
directionsDisplay.setMap(map);
// point the directions to the container for the direction details
directionsDisplay.setPanel(document.getElementById("directionsPanel"));
// add a marker to the map on the geolocated point
marker = new google.maps.Marker({
animation: google.maps.Animation.DROP,
//draggable: true,
map: map
});
var kmlOptions = {
suppressInfoWindows: false,
preserveViewport: true,
map: map
};
transitRoutesLayerKML[0] = new google.maps.KmlLayer('http://mysite/KML/transit_mobile_route1.kml', kmlOptions);
transitRoutesLayerKML[1] = new google.maps.KmlLayer('http://mysite/KML/transit_mobile_route2.kml', kmlOptions);
transitRoutesLayerKML[2] = new google.maps.KmlLayer('http://mysite/KML/transit_mobile_route3.kml', kmlOptions);
transitRoutesLayerKML[3] = new google.maps.KmlLayer('http://mysite/KML/transit_mobile_route4.kml', kmlOptions);
transitRoutesLayerKML[4] = new google.maps.KmlLayer('http://mysite/KML/transit_mobile_route5.kml', kmlOptions);
transitRoutesLayerKML[5] = new google.maps.KmlLayer('http://mysite/KML/transit_mobile_route6a.kml', kmlOptions);
transitRoutesLayerKML[6] = new google.maps.KmlLayer('http://mysite/KML/transit_mobile_route6b.kml', kmlOptions);
// Create the autocomplete object, restricting the search
// to geographical location types.
autocomplete = new google.maps.places.Autocomplete(/** #type {HTMLInputElement} */(document.getElementById('from')), (document.getElementById('to')), { types: ['geocode'] });
// When the user selects an address from the dropdown,
// populate the address fields in the form.
google.maps.event.addListener(autocomplete, 'place_changed', function () {
fillInAddress();
});
}
function fillInAddress() {
// Get the place details from the autocomplete object.
var place = autocomplete.getPlace();
for (var component in componentForm) {
document.getElementById(component).value = '';
}
// Get each component of the address from the place details
// and fill the corresponding field on the form.
for (var i = 0; i < place.address_components.length; i++) {
var addressType = place.address_components[i].types[0];
if (addressType) {
var val = place.address_components[i][addressType];
document.getElementById(addressType).value = val;
}
}
}
function findCurrentPosition() {
if (navigator.geolocation) {
// when geolocation is available on your device, run this function
navigator.geolocation.getCurrentPosition(foundYou, notFound);
autocomplete.setBounds(new google.maps.LatLngBounds(geolocation, geolocation));
} else {
// when no geolocation is available, alert this message
alert('Geolocation not supported or not enabled.');
}
}
function foundYou(position) {
// convert the position returned by the geolocation API to a google coordinate object
var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
// then try to reverse geocode the location to return a human-readable address
geocoder.geocode({ 'latLng': latlng }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
// if the geolocation was recognized and an address was found
if (results[0]) {
// this will update the position of the marker
marker.setPosition(latlng);
// compose a string with the address parts
var address = results[0].address_components[0].long_name + ' ' + results[0].address_components[1].long_name + ', ' + results[0].address_components[3].long_name
// set the located address to the link, show the link and add a click event handler
// onclick, set the geocoded address to the start-point formfield
//$('#from').text(address);
$('#from').val(address);
// call the calcRoute function to start calculating the route
}
} else {
// if the address couldn't be determined, alert and error with the status message
alert("Geocoder failed due to: " + status);
}
});
}
<div id="fromlocationField" data-role="my-ui-field-contain">
<input type="text" id="from" placeholder="From Address, (eg, 10205 - 98street)" value="" /><button id="getCurrentLoc" data-icon="star">Use Current Location</button>
</div>
<div id="tolocationField" data-role="my-ui-field-contain">
<input type="text" id="to" placeholder="To Destination (eg, 10205 - 98street)" value="" />
</div>
<a data-icon="search" data-role="button" href="#" id="getDirectionsSubmit">Get directions</a>
I tried a different method of populating a autocomplete but couldn't get it to resolve at all. This is the closes I've gotten it to work, it works on the 'from' input, but not the 'to' input.
Any advice would be greatly appreciated.
Thanks!
I changed my approach. Since I already have all the geocode information in the application I really just wanted to populate the text boxes. I added this code to the initialize function which does as I would like.
var inputStart = document.getElementById('from');
var inputDestination = document.getElementById('to');
var options = {componentRestrictions: {country: 'ca'}};
new google.maps.places.Autocomplete(inputStart, options);
new google.maps.places.Autocomplete(inputDestination, options);
Related
Using v.3 of the Google geocoder api with a Java back end, Velocity front end and an Oracle db.
Our current spec specifies that when a user selects a marker (lat/lng) that their zoom should be saved as well for future sessions. I can't for the life of me figure out how to do this. I have seen some information about bounds which I think I may be able to use in a hackey way, but I don't want to define the bounds of the map, I just want to save the zoom (like the lat/lng) and be able to pass it to the back end.
map.js
var geocoder;
var map;
var siteLocation;
var marker;
function initMap() {
var lat = parseFloat($("#newLat").val());
var lng = parseFloat($("#newLng").val());
geocoder = new google.maps.Geocoder();
siteLocation = { lat: lat, lng: lng };
map = new google.maps.Map(document.getElementById('map'),
{
center: siteLocation,
zoom: 19,
}
);
//set crosshair
console.log('setting waypoint marker');
crosshair = new google.maps.Marker(
{
position: siteLocation,
map: map,
draggable: false,
shape: { coords: [0, 0, 0, 0], type: 'rect' },
icon: "https://www.daftlogic.com/images/cross-hairs.gif"
}
);
crosshair.bindTo('position', map, 'center');
geocodeLatLng();
}
//use new selection to
function geocodeLatLng() {
var lat = crosshair.getPosition().lat();
var lng = crosshair.getPosition().lng();
var newLocation = crosshair.getPosition();
geocoder.geocode({ location : crosshair.position}, function(results, status) {
if (status == 'OK') {
results[0].geometry.location.lat();
results[0].geometry.location.lng();
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
//get new user selected map options, [drop marker] (optional)
$("#addGeolocation").on("click", function (evt) {
geocodeLatLng();
evt.preventDefault();
var newZoom = map.getZoom();
var newLat = crosshair.getPosition().lat();
var newLng = crosshair.getPosition().lng();
$("#newLat").val(newLat);
$("#newLng").val(newLng);
newLocation = new google.maps.LatLng(newLat, newLng);
map.setCenter(newLocation);
map.setZoom(newZoom);
//make sure no marker exists
if ( marker !== undefined) {
marker.setPosition(newLocation);
} else {
marker = new google.maps.Marker({
position: newLocation,
map: map,
draggable: true
});
}
});
Velocity Macro
#macro(map $ADDRESS)
<script defer
src="https://maps.googleapis.com/maps/api/js?key=${GOOGLE_API_KEY}&callback=initMap">
</script>
<div id="map"></div>
<span class="innerBlock smallBlock" id="map" ></span>
<button type="button" onclick="geocodeLatLng()" id="addGeolocation"> $BTN_ADD_GEOLOCATION</button>
#inp_hidden("newLat" "$context.getSite().getLatitude()")
#inp_hidden("newLng" "$context.getSite().getLongitude()")
#inp_hidden("newZoom")
#end
I am completely stumped. Any ideas? Most of the solutions I have seen involve cookies but we cannot use those. Any advice would be appreciated. Thanks!
I think I understand what you mean but correct me if I'm wrong.
You could save the zoom level in a variable.
var zoom = 16;
and then save this in the local storage
localStorage.setItem("zoomLevel", zoom);
then use getItem method to retrieve it
var savedZoom = localStorage.getItem("zoomLevel");
So if you were planning to have the zoom levels in a select box or something, you can save the users choice into the local storage and then retrieve it when they return by setting to zoom to 'savedZoom' for example.
I'm not completely sure if this is what you were after but hopefully it helps. I've tried not to go into too much detail just incase it isn't.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I am having some issues with my JavaScript in terms of properly returning a set of lat/long values from my function utilizing Google's geocoding API which takes an address and converts it into a lat,lang format which I can pass into Youtube's API to fetch a set of videos uploaded in that general vicinity.
The fix I settled upon is to create a hidden element which gets the lat long value, and then it is passed in. The following is the html tag that I settled on:
<div class="form-group" style="display:none;">
<label for="hidden">Extra:</label>
<input type="text" class="form-control" id="hidden" name="maxResults" placeholder="lat,lang">
</div>
However, my issue was that in my JavaScript, the way I originally had it, it would fail to return the value correctly. If I did an alert inside the function it would should the lat,lang values correctly. However, upon returning those values they are set as undefined for my location: Original code below:
function sendData() {
function initMap() {
var myLatLng = {lat: -25.363, lng: 131.044};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Hello World!'
});
}
var geocoder = new google.maps.Geocoder();
// document.getElementById('submission').addEventListener('click', function() {
// geocodeAddress(geocoder, map);
// });
var myLatLng = {lat: -25.363, lng: 131.044};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
var keyword = $('#q').val();
console.log(geocodeAddress(geocoder,map));
var location = geocodeAddress(geocoder,map);//$('#location').val();
var r = $('#locationRadius').val();
var maxResult = $('#maxResults').val();
console.log("keyword is: " + keyword);
$.get(
"../php/geolocation.php",
{
q: keyword,
location: location,
locationRadius: r,
maxResults: maxResult
},
function (data) {
$('#geolocation-results').html(data);
}
);
}
function buttonClick() {
$("#submission").submit(function(e) {
e.preventDefault();
});
sendData();
}
function geocodeAddress(geocoder, resultsMap) {
var address = document.getElementById('location').value;
geocoder.geocode({'address': address}, function(results, status) {
if (status === 'OK') {
//resultsMap.panTo(results[0].geometry.location);
var marker = new google.maps.Marker({
map: resultsMap,
position: results[0].geometry.location
});
var lat = results[0].geometry.location.lat();
var latS = toString(lat);
var lng = results[0].geometry.location.lng();
var lngS = toString(lng);
var latlngS = latS.concat(",",lngS);
var latlng = new google.maps.LatLng(lat, lng);
resultsMap.setCenter(latlng);
console.log(latlngS);
return latlngS;
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
And below is the fix I settled upon
function geocode() {
var myLatLng = {lat: -25.363, lng: 131.044};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
var geocoder = new google.maps.Geocoder();
geocodeAddress(geocoder, map);
}
function sendData() {
// document.getElementById('submission').addEventListener('click', function() {
// geocodeAddress(geocoder, map);
// });
var keyword = $("#q").val();
var r = $('#locationRadius').val();
var maxResult = $('#maxResults').val();
var location = $("#hidden").val();
console.log("keyword is: " + keyword);
$.get(
"../php/geolocation.php",
{
q: keyword,
location: location,
locationRadius: r,
maxResults: maxResult
},
function (data) {
$('#geolocation-results').html(data);
}
);
}
function buttonClick() {
$("#submission").submit(function(e) {
e.preventDefault();
});
sendData();
}
function geocodeAddress(geocoder, resultsMap) {
var address = document.getElementById('location').value;
geocoder.geocode({'address': address}, function (results, status) {
if (status === 'OK') {
resultsMap.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: resultsMap,
position: results[0].geometry.location
});
var latS = results[0].geometry.location.lat().toString();
var lngS = results[0].geometry.location.lng().toString();
//alert((results[0].geometry.location.lat()));
var latLang = latS.concat(',', lngS);
$('#hidden').val(latLang);
console.log($('#hidden').val());
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
The geocode function is called via an onblur in my html:
<div class="form-group">
<label for="location">location</label>
<input type="text" class="form-control" id="location" name="location" placeholder="Athens, GA" onblur="geocode()">
</div>
So really, to wrap up a rather lengthy code, I want to know how I can avoid having to maintain this disgusting fix in terms of having a hidden in-between form element? Apologies if this is a poorly worded question, I tried my best.
If you want sendData() to be called automatically with the location data as soon as the latLang in geocode's callback is available, then you could:
add a parameter to the function definition as in function sendData(location) and remove the var location = ... initialization and the hidden element because location will instead be set as a parameter to sendData;
and
call sendData(latlang) in geocode's anonymous function callback instead of setting the hidden value, on the line where you are currently setting hidden.
The idea is to create a function that can be called in the geocode callback
and consume its latlang data there instead of storing it globally.
Alternatively, you could set a global variable in a callback instead of the value of a hidden element, but then you can't use it until it is defined. That's no good for automatically chaining the steps, but might be ok if a human watches and pushes a button for the next step. Like the usage of hidden element values, it can lead to synchronization issues.
I am trying to show the distance between two points. but i am facing this error direction request failed due to not found. I googled but not found a solution. Please have a look at my code and tell me if i am doing something wrong.
function initAutocomplete() {
var markerArray = [];
// Instantiate a directions service.
var directionsService = new google.maps.DirectionsService;
// Create a map and center it on Manhattan.
var map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 13,
center: {lat: 40.771, lng: -73.974}
});
// Create a renderer for directions and bind it to the map.
var directionsDisplay = new google.maps.DirectionsRenderer({map: map});
// Instantiate an info window to hold step text.
var stepDisplay = new google.maps.InfoWindow;
// Display the route between the initial start and end selections.
calculateAndDisplayRoute(
directionsDisplay, directionsService, markerArray, stepDisplay, map);
// Listen to change events from the start and end lists.
var onChangeHandler = function() {
calculateAndDisplayRoute(
directionsDisplay, directionsService, markerArray, stepDisplay, map);
};
document.getElementById('start').addEventListener('change', onChangeHandler);
document.getElementById('end').addEventListener('change', onChangeHandler);
}
function calculateAndDisplayRoute(directionsDisplay, directionsService,
markerArray, stepDisplay, map) {
// First, remove any existing markers from the map.
for (var i = 0; i < markerArray.length; i++) {
markerArray[i].setMap(null);
}
// Retrieve the start and end locations and create a DirectionsRequest using
// WALKING directions.
directionsService.route({
origin: document.getElementById('start').value,
destination: document.getElementById('end').value,
travelMode: google.maps.TravelMode.WALKING
}, function(response, status) {
// Route the directions and pass the response to a function to create
// markers for each step.
if (status === google.maps.DirectionsStatus.OK) {
document.getElementById('warnings-panel').innerHTML =
'<b>' + response.routes[0].warnings + '</b>';
directionsDisplay.setDirections(response);
showSteps(response, markerArray, stepDisplay, map);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
function showSteps(directionResult, markerArray, stepDisplay, map) {
// For each step, place a marker, and add the text to the marker's infowindow.
// Also attach the marker to an array so we can keep track of it and remove it
// when calculating new routes.
var myRoute = directionResult.routes[0].legs[0];
for (var i = 0; i < myRoute.steps.length; i++) {
var marker = markerArray[i] = markerArray[i] || new google.maps.Marker;
marker.setMap(map);
marker.setPosition(myRoute.steps[i].start_location);
attachInstructionText(
stepDisplay, marker, myRoute.steps[i].instructions, map);
}
}
function attachInstructionText(stepDisplay, marker, text, map) {
google.maps.event.addListener(marker, 'click', function() {
// Open an info window when the marker is clicked on, containing the text
// of the step.
stepDisplay.setContent(text);
stepDisplay.open(map, marker);
});
}
Html side :
<input id="start" class="controls" type="text"
placeholder="picup lock">
<input id="end" class="controls" type="text"
placeholder="drop off">
Based from this documentation, error NOT_FOUND indicates at least one of the locations specified in the request's origin, destination, or waypoints could not be geocoded.
Make sure that point1 and point3 are not empty. The API doesn't know how to create a route from "" to "".
Check this related ticket and tutorial.
I had the same issue yesterday, using the API via C# httpClient. But the same request worked fine in a browser. After a bit of debugging I found out that it only worked if I sent Accept-Language header in the httpClient…
UPDATE
when i click green marker,it's display address of location.can i change it?
LATER EDIT :
is it possible to open popup on click of a marker from the directions service?
or try the other way like only hide a marker from the directions service(green marker) and display only red marker(hide only green marker not it's route)?is it good way?
if not possible, please suggest some alternative ideas.
OLDER:
i have a two types of marker on google map.the red marker is normal marker which represent location.and green marker is route marker(its represent many of waypoints of the map).
I modify the infowindow with textbox.which is open on click red marker.
actually i am trying to do is, first i place multiple markers on google map then i draw route between this markers.this thing is done.reminder thing is on click green marker one popup is opened in which user enter price and then click the button.then i got this value and store it to database.
the problem is:
(1) how to open same infowindow on click of green marker?
in short,how to write a code for display infowindow on click of of green marker.
how to find click event of green marker?
code is:
<script type="text/javascript">
var markerarray=new Array();
//for way points
var waypts=[];
//array in json format for placing multiple marker
var locations = <?php echo json_encode($lat1);?>;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 11,
center: new google.maps.LatLng(23.0171240, 72.5330533),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
<!-- ************* for placing markers ************ -->
var marker, i;
for (i = 0; i < locations.length; i++)
{
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][3], locations[i][4]),
map: map //enable if you want marker
});
//push value into way points
waypts.push({
location:locations[i][0],
stopover:true
});
//create array for polyline
markerarray[i] = marker.getPosition();//(Array(locations[i][5], locations[i][6]));
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
var data='<div style="height:150px !important"><table><tr><td>Enter Price</td></tr><tr><td><input type="text" name="prc" id="prc" /></td></tr></table></div>';
infowindow.setContent(data);
infowindow.open(map, marker);
}
})(marker, i));
}
<!-- ************** for route between markers ******************* -->
var first=locations[locations.length-1][0];
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
//directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay = new google.maps.DirectionsRenderer({
polylineOptions: {
strokeColor: 'red',//"black",
strokeOpacity: 1.0,
strokeWeight: 3
}
});
var start = locations[0][0];//"Bopal, Ahmedabad, Gujarat, India";
var end = locations[locations.length-1][0];//"Nikol, Ahmedabad, Gujarat, India";
//remove start destination from array
waypts.shift();
//remove end destination from array
waypts.pop();
var request = {
origin:start,
destination:end,
waypoints:waypts,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
directionsDisplay.setMap(map);
</script>
Thanks in advance.
It is not impossible but it will take some time for code, The way is if you are using for mobile device then you need to accelerator from your device and call geolocation function on position change I think you understand and the second method is from purely javascript method for that you need to call your geolocation function within set Interval understand also draw line separately from marker your marker function only calls within set Intervals for getting your current location with infowindow. Example is :
var map;
function initialize() {
var mapOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
//keep this in setInterval
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Location found using HTML5.'
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
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);
}
//close here your set interval
google.maps.event.addDomListener(window, 'load', initialize);
It's possible. You can hide the default marker such that you can build a custom marker on the clicked location. This code is to hide the marker.
var rendererOptions = {
suppressMarkers : true
}
var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
I have a set of jQuery UI tabs that each load project.php using ajax. Depending on the parameters passed to the script, a different Google map is displayed using the following JavaScript inside project.php:
var tab_index = $('#tabs').tabs('option', 'selected');
$('.site_map:visible').css('height','300px');
MapID = $('.site_map:visible').attr('id');
if (MapID !== 'map-new'){
var map_id = 'map-'+tab_index;
$('.site_map:visible').attr('id', map_id);
} else {
MapNewSite();
}
var latlng = new google.maps.LatLng(19,-70.4);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
arrMaps[tab_index] = new google.maps.Map(document.getElementById("map-" + tab_index), myOptions);
arrInfoWindows[tab_index] = new google.maps.InfoWindow();
placeMarker($('.site_details:visible .inpLat').val(), $('.site_details:visible .inpLng').val(), tab_index);
function MapNewSite(){
arrMaps[tab_index] = new google.maps.Map(document.getElementById("map-new"), myOptions);
placeMarker(19,-70.4,tab_index);
arrInfoWindows[tab_index] = new google.maps.InfoWindow();
}
Each map loaded using parameters returned by a query of my database loads without any problems. However, in one last instance, I load project.php in a tab without any parameters so as to have a blank tab for users to manipulate. The signal that the map is not to be loaded using database coordinates is that the id of its div is "map-new".
The map generated in this tab loads, but then gives me the "a is null" error which usually means it couldn't find a div with the id specified to initialize the map. What is causing this error even after the map has loaded? How do I stop the error from occurring?
Here is the JavaScript in the parent page containing the tab site:
var arrMaps = {};
var arrInfoWindows = {};
var arrMarkers = {};
function placeMarker(lat, lng, tab_index){
map = arrMaps[tab_index];
var bounds = new google.maps.LatLngBounds();
var latlng = new google.maps.LatLng(
parseFloat(lat),
parseFloat(lng)
);
bounds.extend(latlng);
createMarker(latlng, tab_index);
map.fitBounds(bounds);
zoomChangeBoundsListener =
google.maps.event.addListener(map, 'bounds_changed', function(event) {
if (this.getZoom()){
this.setZoom(10);
}
google.maps.event.removeListener(zoomChangeBoundsListener);
});
}
function createMarker(latlng, tab_index) {
var html = 'Click here to move marker';
arrMarkers[tab_index] = new google.maps.Marker({
map: arrMaps[tab_index],
position: latlng
});
arrInfoWindows[tab_index] = new google.maps.InfoWindow();
google.maps.event.addListener(arrMarkers[tab_index], 'click', function() {
arrInfoWindows[tab_index].setContent(html);
arrInfoWindows[tab_index].open(arrMaps[tab_index], arrMarkers[tab_index]);
});
}
$(function() {
$( "#tabs" ).tabs({
ajaxOptions: {
error: function( xhr, status, index, anchor ) {
$( anchor.hash ).html(
"Couldn't load this tab. We'll try to fix this as soon as possible. " +
"If this wouldn't be a demo." );
}
},
cache: true
});
});
Take a look to http://www.pittss.lv/jquery/gomap/. Easy to use and very powerful. I myself use it.
It turns out I was accidentally initializing the map both inside the if and outside of it.