Google maps API v3 initialize function - google-maps-api-3

I'd like to lean up my initialize() function... but every time I do, it breaks my code.
I'm eventually trying to do something like this, where I have a sidebar with stuff that's directly related to the markers on the map, AJAX'd in... Firstly, I'd like to be able to put other functions outside of the initialize() function. This works fine:
<script>
function initialize() {
// create the map object
var mapOptions = {
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
// create your location marker
var mylocOptions = {
draggable: true,
animation: google.maps.Animation.DROP,
icon: new google.maps.MarkerImage('//maps.gstatic.com/mapfiles/mobile/mobileimgs2.png',
new google.maps.Size(22,22),
new google.maps.Point(0,18),
new google.maps.Point(11,11)),
title: "You are here..."
};
var myloc = new google.maps.Marker(mylocOptions);
// get location information from browser, or from user input, or from database
<% if !signed_in? || !current_user.loc %>
if (navigator.geolocation) navigator.geolocation.getCurrentPosition(function(pos) {
var me = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
myloc.setPosition(me);
myloc.setMap(map);
map.setCenter(me);
$.ajax({
data: { me: me.toString() },
type: 'POST',
url: '/set-location'
})
}, function(error) {
var address = prompt('Where are you looking?');
geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var me = results[0].geometry.location
myloc.setPosition(me);
myloc.setMap(map);
map.setCenter(me);
} else {
alert("Geocode was not successful for the following reason: " + status);
};
});
});
<% else %>
var me = new google.maps.LatLng(<%= current_user.loc %>);
myloc.setPosition(me);
myloc.setMap(map);
map.setCenter(me);
map.setZoom(12);
<% end %>
// watch for marker movement, and update location accordingly
var oldPos = myloc.getPosition();
google.maps.event.addListener(myloc, "dragend", function(e){
revGeo = new google.maps.Geocoder();
var newPos = myloc.getPosition();
$.ajax({
data: { me: newPos.toString() },
type: 'GET',
url: '/set-location'
})
if(oldPos != newPos)
revGeo.geocode({'latLng': newPos}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
$('#loc').html(results[1].formatted_address);
}
} else {
alert("Geocoder failed due to: " + status);
}
});
oldPos = newPos;
});
// when creating an event, check for event location,
// verify it's existance and put a marker down on the map
$(document).on('focusout', '#event_location', function() {
geocoder = new google.maps.Geocoder();
address = document.getElementById("event_location").value;
geocoder.geocode({ 'address': address }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var coords = results[0].geometry.location;
map.setCenter(coords);
var marker = new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP,
position: coords
});
$('#coords').html('coordinates: ' + coords)
$('#event_geocode').val(coords.toString())
} else {
alert(status + " for " + address);
};
});
});
}
</script>
... but I'm sure it can be broken up. Any ideas of what I'm doing wrong?

Related

Code works in EDIT view and not SAVED page

My mission: Create a map from list such as :
When editing a SharePoint page (edit mode/view) the map throws no errors in the console. But as I go to view the final saved page the map I get this error in the console:
Event Page.aspx:668 Uncaught TypeError: Cannot read property 'get_current' of undefined
at retrieveListItems (Event Page.aspx:668)
at Event Page.aspx:789
This error points to this line :
var clientContext = new SP.ClientContext.get_current();
It seems like the PAGE is missing some resources that get added when I'm in EDIT MODE.
This code gets the info from the list to pass to the map script.
function retrieveListItems() {
var listName = "North East Events";
var clientContext = new SP.ClientContext.get_current();
var oList = clientContext.get_web().get_lists().getByTitle(listName);
this.website = clientContext.get_web();
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View><Query><Where><Geq><FieldRef Name=\'ID\'/>' +
'<Value Type=\'Number\'>1</Value></Geq></Where></Query><RowLimit>50</RowLimit></View>');
collListItem = oList.getItems(camlQuery);
clientContext.load(this.website);
clientContext.load(this.collListItem);
clientContext.executeQueryAsync(Function.createDelegate(this, onQuerySucceeded), Function.createDelegate(this, onQueryFailed));
}
function onQuerySucceeded(sender, args) {
var geocoder;
var map;
var bounds = new google.maps.LatLngBounds();
var listItemInfo = '';
var locations = [];
var listItemEnumerator = collListItem.getEnumerator();
while (listItemEnumerator.moveNext()) {
var oListItem = listItemEnumerator.get_current();
var eventName = oListItem.get_item('Title');
var eventAddress = oListItem.get_item('WorkAddress');
var eventURL = website.get_url() + '/' + 'Lists/North East Reports/DispForm.aspx?ID=' + oListItem.get_id();
var newLocations = [eventName, eventAddress, eventURL];
locations.push(newLocations);
}
google.maps.event.addDomListener(window, "load", initialize);
function initialize() {
map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
geocoder = new google.maps.Geocoder();
for (i = 0; i < locations.length; i++) {
geocodeAddress(locations, i);
}
}
function geocodeAddress(locations, i) {
var title = locations[i][0];
var address = locations[i][1];
var url = locations[i][2];
geocoder.geocode({
'address': locations[i][1]
},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
icon: 'http://maps.google.com/mapfiles/ms/icons/blue.png',
map: map,
position: results[0].geometry.location,
title: title,
animation: google.maps.Animation.DROP,
address: address,
url: url
})
infoWindow(marker, map, title, address, url);
bounds.extend(marker.getPosition());
map.fitBounds(bounds);
} else {
alert("geocode of " + address + " failed:" + status);
}
});
}
function infoWindow(marker, map, title, address, url) {
google.maps.event.addListener(marker, 'click', function() {
var html = "<div><h3>" + title + "</h3><p>" + address + "<br></div><a href='" + url + "'>View location</a></p></div>";
iw = new google.maps.InfoWindow({
content: html,
maxWidth: 350
});
iw.open(map, marker);
});
}
function createMarker(results) {
var marker = new google.maps.Marker({
icon: 'http://maps.google.com/mapfiles/ms/icons/blue.png',
map: map,
position: results[0].geometry.location,
title: title,
animation: google.maps.Animation.DROP,
address: address,
url: url
})
bounds.extend(marker.getPosition());
map.fitBounds(bounds);
infoWindow(marker, map, title, address, url);
return marker;
}
}
function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
retrieveListItems();

Can't get Google Maps api v3 to display markers from xml file

I should have on my hands what is proper working JS and an xml file...I'm simply trying to take advantage of the huge database of locations that has been offered up as free for everyone to use - located # http://www.craftbeer.com/breweries/brewery-locator/find-a-us-brewery
I'm tried using their maps.js and xml file...but all I end up with is a blank maps screen...
Here is the Javascript...
/*********************************************
**Google Maps Custom API work**
This code can be reused on any site to display a local map of breweries from our local iMis dump, as well as pull in beermapping.
Hey! Don't forget to include API in functions.php! Function is conditionally initialized in footer.php
*/
//Set up variables to create marker
var gmarkers = [];
var mapMarkers = [];
var geocoder = new google.maps.Geocoder();
var icon = 'http://www.craftbeer.com/wp-content/uploads/marker.png';
//Initialize Map
function view_map(xml_file, latitude, longitude, varZoom) {
console.log('view map');
map = new google.maps.Map(document.getElementById("map_canvas"), { //Create the map, Set Default Zoom level and type
center: new google.maps.LatLng(latitude, longitude),
zoom: varZoom,
mapTypeId: 'roadmap',
panControl: true,
zoomControl: true,
mapTypeControl: false,
scaleControl: true,
streetViewControl: false,
overviewMapControl: false
});
//-- Listeners --//
google.maps.event.addListener(map, 'center_changed', function() {
console.log('center changed');
//clearMarkers();
});
google.maps.event.addListenerOnce(map, 'tilesloaded', function(){
//this part runs when the mapobject is created and rendered
console.log("loaded");
$("#loading-screen").fadeOut(250, function(){});
$("#loading-icon").fadeOut();
//google.maps.event.addListenerOnce(map, 'tilesloaded', function(){ });
});
//console.log(xml_file);
var download_file = xml_file; //this variable is passed in so we can re-use this script
//Pull in the XML feed
downloadUrl(download_file, function(data) {
console.log("downloading xml");
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
//Loop through all markers in the XML file
for (var i = 0; i < markers.length; i++) {
var state = markers[i].getAttribute("state");
var x = markers[i].getAttribute("lat");
var y = markers[i].getAttribute("lng");
if ( state != 'PR' && state != 'VI' && state != 'GU' && x != "" ){
//console.log(state);
var ids = parseFloat(markers[i].getAttribute("id"));
var z = new google.maps.LatLng(x,y,i);
//console.log(x);
var _id = markers[i].getAttribute("id");
var name = markers[i].getAttribute("company");
var address = markers[i].getAttribute("address");
var city = markers[i].getAttribute("city");
var zip = markers[i].getAttribute("zip");
var phone = markers[i].getAttribute("phone");
var url = markers[i].getAttribute("url");
var brewery_type = markers[i].getAttribute("type");
var member_type = '';
var member_type = markers[i].getAttribute("member_type");
var offer = markers[i].getAttribute("offer");
var html = "<div class='bubble_content'><strong>" + name + "</strong><br />";
html += address + "<br/>" + city + ", " + state + " " + zip;
if(url) html += "<br /><br /><a href='http://" + url + "' target='_blank'>Visit Web Site</a></div>";
//var marker = createMarker(ids, z, title, contentstring);
var marker = new google.maps.Marker({
position: z,
map: map,
title: name,
icon: icon,
html: html,
zindex: i
});
//Add a listener for every icon click
google.maps.event.addListener(marker,'click',function(){
infowindow.setContent(this.html);
infowindow.open(map,this);
//map.setZoom(10);
//map.setCenter(this.getPosition());
console.log(this);
});
gmarkers[ids] = marker;
mapMarkers.push(marker);
if( x && y ){
//console.log(ids);
var infowindow = new google.maps.InfoWindow({content: html});
}
/* google.maps.event.addListener(marker, 'click', function() {
console.log('marker clicked');
});
*/
//bounds.extend(z);
//map.fitBounds(bounds);
}//end check for US states only!
} //end for loop
var mcOptions = {gridSize: 60, maxZoom: 9};
var markerCluster = new MarkerClusterer(map, mapMarkers, mcOptions); //this is the function that groups the icons into markers
});
} //End full function to create map
/*
* FUNCTION
*
* click to bring up one icon when clicked from the list.
*/
function myclick(i){
console.log('clicked a title ' + i);
smoothScroll("#primary");
var lat = parseFloat(gmarkers[i].position.k);
var lng = parseFloat(gmarkers[i].position.B);
console.log(lat);
map.setCenter({lat: lat, lng: lng});
map.setZoom(13);
google.maps.event.trigger(gmarkers[i], 'click');
};
function createMarker(ids, z, title, contentstring){
console.log('createMarker');
var marker = new google.maps.Marker({
position: z,
map: map,
title: title,
html: contentstring,
icon: 'http://maps.google.com/mapfiles/ms/icons/orange-dot.png'
});
google.maps.event.addListener(marker,'click',function(){
infowindow.setContent(this.html);
infowindow.open(map,marker);
});
gmarkers[ids] = marker;
//console.log(gmarkers[ids]);
};
/*
* FUNCTION findAddress()
*
* given an adress string, zoom the map to the proper state
*/
function findAddress(position) {
//Let's determind if we have a state (address) or LatLng
var addressStr = $("#state_select li.active").data('state-id');
if (addressStr != 'Select a State') address = "US State of "+addressStr;
if(position) {
var lat = parseFloat(position['latitude']);
var lng = parseFloat(position['longitude']);
var latlng = new google.maps.LatLng(lat, lng);
//console.log(latlng);
}
//Now let's geocode - two different cases
if (geocoder && position) { //If LatLng
//console.log('near me');
geocoder.geocode( { 'location': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
if (results && results[0] && results[0].geometry && results[0].geometry.viewport && addressStr!="ON" && addressStr!="INT") {
map.fitBounds(results[0].geometry.viewport); //resize map to fit.
map.setZoom(13);
}
} else {
alert("No results found");
}
}
});
} else if (geocoder && address!="") { //If State
//console.log('by state');
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
if (results && results[0] && results[0].geometry && results[0].geometry.viewport && addressStr!="ON" && addressStr!="INT") {
map.fitBounds(results[0].geometry.viewport); //resize map to fit.
map.setZoom(6);
}
} else {
alert("No results found");
}
}
});
} else {
//alert("Geocode was not successful for the following reason: " + status);
}
}
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('GET', url, true);
request.send(null);
}
function doNothing() {}
And here is the link to the xml file....
http://www.straighttothepint.com/wp-content/uploads/wp-google-maps/Google_Map_APIs.xml
I've spent days doing google searches and testing different sections of code to at least get a basic google map to show up via the xml file markers...but to no avail - Any help would be tremendously appreciated!!
~Cheers
EDIT:
Everything worked as expected once I included the following script inline on the page prior to calling the maps.js file. Thanks everyone!
<script>
$(document).ready(function(){
var latitude = 39.300299;
var longitude = -97.382812;
view_map('./uploads/your_xml_file.xml', latitude,longitude,4);
//scripts to handle mapping are in js/mylibs/map.js.php
});
</script>
Looking at the html and the code you provided above I constructed a fiddle for you:
http://jsfiddle.net/loanburger/qafsex5x/
I added two markers in an xml string at the top in the fiddle.
I basically parse the xml doing this:
var markers = $(xml).find("marker");
Its then simply the same for loop you had:
for (var i = 0; i < markers.length; i++)
{
...
}
The fiddle will show you the markers.

Implementing google place autocomplete

This is my code for places autocomplete and search.
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places">
</script>
<script>
var geocoder;
var map;
function initialize() {
var input = document.getElementById('address');
var options = {
componentRestrictions: {country: "in"}
};
var autocomplete = new google.maps.places.Autocomplete(input,options);
geocoder = new google.maps.Geocoder();
//var latlng = new google.maps.LatLng(18.52043030000, 73.85674369999);
var mapOptions = {
zoom: 15,
//center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
map = new google.maps.Map(document.getElementById('googleMap'), mapOptions);
}
function codeAddress() {
var address = document.getElementById('address').value;
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({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
This is my html code.
<input id="address" type="textbox" size="30">
<input type="button" value="Search" onclick="codeAddress()">
It is working fine but I dont want to user to click the button. When suggestions appeared, and when user select any of suggestion options, map will have to navigate to that place. How do I do this???
When User select any option from dropdown, map should navigate to that place.
Take a look at this example and the implementation of the place_changed event.
var place = autocomplete.getPlace();
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
}
This way you can pan the map to the location of the autocomplete result.
This is my working code..
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places">
</script>
<script>
var geocoder;
var map;
function initialize() {
var input = document.getElementById('address');
var options = {
componentRestrictions: {country: "in"}
};
var autocomplete = new google.maps.places.Autocomplete(input,options);
geocoder = new google.maps.Geocoder();
//var latlng = new google.maps.LatLng(18.52043030000, 73.85674369999);
var mapOptions = {
zoom: 15,
//center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
map = new google.maps.Map(document.getElementById('googleMap'), mapOptions);
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29)
});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
if (!place.geometry) {
return;
}
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17); // Why 17? Because it looks good.
}
marker.setIcon(/** #type {google.maps.Icon} */({
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(35, 35)
}));
marker.setPosition(place.geometry.location);
marker.setVisible(true);
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
infowindow.open(map, marker);
});
}
function codeAddress() {
var address = document.getElementById('address').value;
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({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Now user can select option from dropdown and map will navigate to that place. And also on search button click.
Hope this might help you
function initialize(){
var mapOptions = {//Map Properties
zoom:12,
center: Bangalore
};
googleMap = new google.maps.Map(document.getElementById('map-holder'),mapOptions);//map-holder is a div which holds map in my html
var defaultBounds = new google.maps.LatLngBounds(//bounds for Bengaluru
new google.maps.LatLng(12.7342888,77.3791981),
new google.maps.LatLng(13.173706,77.8826809)
);
googleMap.fitBounds(defaultBounds);
var input = (document.getElementById('searchInput'));//search input element
googleMap.controls[google.maps.ControlPosition.TOP_LEFT].push(input);//binding it to map
var searchBox = new google.maps.places.SearchBox((input));
google.maps.event.addListener(searchBox, 'places_changed', function() {//triggers when search is performed
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
var bounds = new google.maps.LatLngBounds();
for (var i = 0, place; place = places[i]; i++) {
bounds.extend(place.geometry.location);
//googleMap.fitBounds(place.geometry.viewport);
}
googleMap.fitBounds(bounds);
});
google.maps.event.addListener(googleMap, 'bounds_changed', function() {
var bounds = googleMap.getBounds();
searchBox.setBounds(bounds);
})
}

google map autocomplete field fetch address from database

I am running a script that has autocomplete field and fethes the address from google in the autocomplete firld.
I want to fetch the addresses in autocomplete field via database and then show the locations on map.
Here is my code :
$(document).ready(function(){
var mapOptions = {
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: new google.maps.LatLng(43.890423,-79.417732)
};
var map = new google.maps.Map(document.getElementById("map"),mapOptions);
var geocoder = new google.maps.Geocoder();
$(function() {
$("#searchbox").autocomplete({
source: function(request, response) {
if (geocoder == null){
geocoder = new google.maps.Geocoder();
}
geocoder.geocode( {'address': request.term }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var searchLoc = results[0].geometry.location;
var lat = results[0].geometry.location.lat();
var lng = results[0].geometry.location.lng();
var latlng = new google.maps.LatLng(lat, lng);
var bounds = results[0].geometry.bounds;
geocoder.geocode({'latLng': latlng}, function(results1, status1) {
if (status1 == google.maps.GeocoderStatus.OK) {
if (results1[1]) {
response($.map(results1, function(loc) {
return {
label : loc.formatted_address,
value : loc.formatted_address,
bounds : loc.geometry.bounds
}
}));
}
}
});
}
});
},
select: function(event,ui){
var pos = ui.item.position;
var lct = ui.item.locType;
var bounds = ui.item.bounds;
if (bounds){
map.fitBounds(bounds);
}
}
});
});
});
Any help is greately appreciated.
I am not much aware of google api and maps.

google map marker not defined wordpress

I am using the code below in the Ultimatum WordPress theme template along with some PHP code to provide the dynamic values required for the map. I am getting a marker not defined error. The code is placed 3/4 of the page down within div tags, rather than in the header or footer because it is only used on the one page. I've tried a couple of suggestions I found with no luck.
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
//<![CDATA[
var geocoder;
var map;
function initialize ()
{
geocoder = new google.maps.Geocoder();
var address = document.getElementById('Property').value;
var city = document.getElementById('City').value;
var postal_code = document.getElementById('PostalCode').value;
var address_google_map = address + ', ' + city + ', ON ' + postal_code;
var myOptions =
{
zoom: 15,
mapTypeControl: true,
zoomControl: true,
zoomControlOptions:
{
style: google.maps.ZoomControlStyle.SMALL
},
StreetViewControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var info_text = address + '<br />' + city + ' ON';
var info_window = new google.maps.InfoWindow
({
content: info_text
});
var map = new google.maps.Map(document.getElementById('google_map'), myOptions);
geocoder.geocode( { 'address': address_google_map}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.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);
}
});
google.maps.event.addListener(marker, 'click', function()
{
info_window.open(map, marker);
});
}
window.onload = function() {
initialize();
}
//]]>
</script>
The marker is local to the Geocoder callback routine. Move the click listener definition inside the function where it is in scope.
geocoder.geocode( { 'address': address_google_map}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
google.maps.event.addListener(marker, 'click', function()
{
info_window.open(map, marker);
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}

Resources