Dynamically create a Google Maps API V3 Script function - javascript

So I'm trying to use a combination of Google Autocomplete with Google Maps API V3.
A user will enter an address into an address field (page1), click 'Next', and then a lightbox (page2) will appear with the Map of the address that they entered.
So what will happen is that the lat + long (from page1) of the address will being passed into the lightbox URL (page2) as query params. The script below will need to build itself on page-load, using the lat+long.
Below is the default Google Maps
<script>
function initMap() {
var address = {lat: lat_address, lng: lng_address};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: address
});
var marker = new google.maps.Marker({
position: address,
map: map
});
}
</script>
What I'm unsure about is how to build a script on page-load. Could anyone advise please? Thank you!

Actually I just solved this utilizing the function getQueryVariable to get the value of each query param from the URL, and then using it in the initMap to pass variables on page-load.
<script>
//Function that allows easy access to param->value
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];}
}
return(false);
}
//Initialize the GMap
function initMap() {
var latAddress = getQueryVariable('lat_address');
var latAddress = parseInt(latAddress);
var lngAddress = getQueryVariable('lng_address');
var lngAddress = parseInt(lngAddress);
var address = {lat: latAddress, lng: lngAddress};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: address
});
var marker = new google.maps.Marker({
position: address,
map: map
});
}
</script>

Related

Knockout function and Google Map

I am trying to create a map with different locations and I am using knockout binding to display some features on my html view.
I have a function that enables me to create various locations.
I want each location to have its own marker. When rendering the map, I display some defaults locations. But I have this error: Uncaught ReferenceError: google is not defined
Here is my code.
defaultMarkers =[
new Locations("Ike's Food & Cocktails","(612) 746-4537","50 S 6th St","",44.97818705436708,-93.27229499816895),
new Locations("Eli's East Food & Cocktails","(612) 331-0031","815 E Hennepin Ave","#",44.99128282822349,-93.24738264083862),
new Locations("Midnord Empanada Food truck","unavailable","unavailable","#",44.97596890779807,-93.27159452192403),
new Locations("Maruso Street Food Bar","(612) 333-0100", "715 E Hennepin Ave","#",44.97760063074655,-93.2754345812601),
new Locations("The House Of Hunger Food Truck","unavailable","unavailable","#",44.97611524414878,-93.27146677068872)];
var map;
function initMap() {
var mapOptions = {
center: {lat: 38.9165087, lng: -77.2482606},
zoom: 13
}
map = new google.maps.Map(document.getElementById('map'), mapOptions);
// add defaults markers on map
updateMap(map, defaultMarkers);
}
function Locations(name, contact, fulladress, url, lat, lng){
var self = this;
self.name= name;
self.contact = contact;
self.url = url;
self.fulladress = fulladress;
self.lat = lat;
self.lng = lng;
self.showMe = ko.observable(true);
self.marker = new google.maps.Marker({ // HERE IS THE LINE WHERE THE ERROR OCCUR
position: new google.maps.LatLng(lat, lng),
map: map,
});}
function MapViewModel() {
var self = this;
self.listVenues = ko.observableArray(defaultMarkers);
}
Can you help me figure out where I am doing wrong?
.
Make sure your script is:
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&key=APIKEY"></script>
Not including the type="text/javascript" may be messing you up.

google map api, link to URL

Sorry for asking a simple question I surely can find easily by reading the API docs, but a client just asked me this in general, and I would like to answer him asap.
Situation:
I have a custom map created, with public (or restricted to user) access, where are different markers.
Q1)Is it possible to create markers via the API using e.g. custom data from our database?
Q2)Ist it possible to add a URL to a marker, so that a user clicks on it and gets to a specific site, where he can e.g. vote for this location? (just as an example)
Thanks in advance to everyone, and once more sorry not to look closer by myself
Cheers,
Phil
Following Function Will Create Marker
<script type="text/javascript">
// Standard google maps function
function initialize() {
var myLatlng = new google.maps.LatLng(40.779502, -73.967857);
var myOptions = {
zoom: 12,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
TestMarker();
}
// Function for adding a marker to the page.
function addMarker(location) {
marker = new google.maps.Marker({
position: location,
map: map
});
}
// Testing the addMarker function
function TestMarker() {
CentralPark = new google.maps.LatLng(37.7699298, -122.4469157);
addMarker(CentralPark);
}
For Clicking and URL Use Following Technique
var points = [
['name1', 59.9362384705039, 30.19232525792222, 12, 'www.google.com'],
['name2', 59.941412822085645, 30.263564729357767, 11, 'www.amazon.com'],
['name3', 59.939177197629455, 30.273554411974955, 10, 'www.stackoverflow.com']
];
var marker = new google.maps.Marker({
...
zIndex: place[3],
url: place[4]
});
google.maps.event.addListener(marker, 'click', function() {
window.location.href = this.url;
});

Get Search Location from Index Page & Zoom to Location on Map Page

I'm trying to setup a redirect from the index page to the map page, so if a user searches for an address using the Places Autocomplete library, they get redirected to the map page with the location that they searched for. The index page does not include a map, but just the search bar with Places Autocomplete library.
The function I've setup on the index page is as follows:
var place;
function indexSearch() {
// Get Address Field and Attach Places Autocomplete
var input = document.getElementById('autocomplete');
var autocomplete = new google.maps.places.Autocomplete(input);
// Get Place When Place_Changed Event if Fired
google.maps.event.addListener(autocomplete, 'place_changed', function () {
place = autocomplete.getPlace();
if (typeof place !== 'undefined') {
window.location.href = 'map';
// Don't know what to do here
// as I can't use map.panTo(place.geometry.location) because
// map does not exist on index page.
}
});
// Erase Previous Address if Search Bar is Clicked
inputIndex.onclick = function () {
inputIndex.value = '';
}
}
Do I need to include something in the initialize() function which is responsible for setting up the map?
function initialize() {
var mapOptions = {
zoom: 17,
center: {
lat: -33.8666,
lng: 151.1958
},
disableDefaultUI: true
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
// Catch place and pan map to its location
}
Edit: At least provide a reason for downvote.
I'm looking into using localStorage or sessionStorage. Pass the lat and lng to either of those, and retrieve the location when the map page is loading. Is this an optimal solution? Will update with answer once I have the solution.
Here's what I ended up doing. It's working for me. Hope it helps someone in future.
In indexSearch() function, set a key in sessionStorage to store lat and lng of place that is searched. Capture this information when the place_event is fired.
var place;
function indexSearch() {
// Get Address Field and Attach Places Autocomplete
var input = document.getElementById('autocomplete');
var autocomplete = new google.maps.places.Autocomplete(input);
// Get Place When Place_Changed Event if Fired
google.maps.event.addListener(autocomplete, 'place_changed', function () {
place = autocomplete.getPlace();
if (typeof place !== 'undefined') {
window.location.href = 'map';
// Set key in sessionStorage
sessionStorage.myLat = place.geometry.location.lat();
sessionStorage.myLat = place.geometry.location.lng();
}
});
// Erase Previous Address if Search Bar is Clicked
inputIndex.onclick = function () {
inputIndex.value = '';
}
}
Then in initialize() function, check to see if the key exists. If it does, take the user to that location.
function initialize() {
var mapOptions = {
zoom: 17,
center: {
lat: -33.8666,
lng: 151.1958
},
disableDefaultUI: true
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
// Get place from sessionStorage if its exists & pan map to its location
var placeLat = sessionStorage.getItem('myLat');
var placeLng = sessionStorage.getItem('myLng');
if (placeLat && placeLng) {
var searchedPlace = new google.maps.LatLng(placeLat, placeLng);
map.setCenter(searchedPlace);
map.setZoom(15);
}
}

Update markers with current position on Google Map API

I am learning to use javascript right now with Rails and I'm having some issues with updating my markers according to my current position using AJAX. I believe the ready page:load is not running the updated coords that have been attached as a data-attribute, coords since the page is not technically reloading. How can I use my current position data and update it with events with longitude/latitude values?
var map;
$(document).on('ready page:load', function() {
if ("geolocation" in navigator) {
myMap.init();
var coords = $('#map-canvas').data('coords');
if (coords){
myMap.addMarkers(coords);
}
}
});
myMap.init = function() {
if(navigator.geolocation){
var mapOptions = {
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
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
});
var marker = new google.maps.Marker({
position: new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
map: map
});
map.setCenter(pos);
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
$.ajax({
url:"/all_events",
method: "GET",
data: {
latitude: latitude,
longitude: longitude
},
dataType: 'script'
});
});
} else {
document.getElementById('map-canvas').innerHTML = 'No Geolocation Support.';
}
};
myMap.addMarkers = function(coords){
var image = "http://maps.google.com/mapfiles/ms/icons/yellow-dot.png"
coords.forEach(function(coord){
var myMarker = new google.maps.Marker({
position: new google.maps.LatLng(coord.latitude, coord.longitude),
map: map,
icon: image
});
});
}
In order to make your script work in the way you want please try out the following steps:
Put your foreach loop in a function and call it at the end of your successive AJAX callbacks.
Load the AJAX once the Google Maps have finished loading completely. If Google Maps library has not finished loading than you wont be able to create a Google LatLng object, this is what is probably happening over here.
Hope this would help

How to set google map marker by latitude and longitude and provide information bubble

The following sample code provided by google maps api
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(40.77627, -73.910965);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
the following only shows google map of the location without a marker.
I was wondering how I can place a marker by giving latitude/longitude parameters?
And how is it possible to store my own information pulled from a database on that marker?
Here is a JSFiddle Demo that shows you how to set a google map marker by Lat Lng and also when click would give you an information window (bubble):
Here is our basic HTML with 3 hyperlinks when clicked adds a marker onto the map:
<div id="map_canvas"></div>
<a href='javascript:addMarker("usa")'>Click to Add U.S.A</a><br/>
<a href='javascript:addMarker("brasil")'>Click to Add Brasil</a><br/>
<a href='javascript:addMarker("argentina")'>Click to Add Argentina</a><br/>
First we set 2 global variables. one for map and another an array to hold our markers:
var map;
var markers = [];
This is our initialize to create a google map:
function initialize() {
var latlng = new google.maps.LatLng(40.77627, -73.910965);
var myOptions = {
zoom: 1,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
We then create 3 lat lng locations where we would like to place our markers:
var usa = new google.maps.LatLng(37.09024, -95.712891);
var brasil = new google.maps.LatLng(-14.235004, -51.92528);
var argentina = new google.maps.LatLng(-38.416097, -63.616672);
Here we create a function to add our markers based on whatever is passed onto it. myloc will be either usa, brasil or argentina and we then create the marker based on the passed param. With in the addMarker function we check and make sure we don't create duplicate marker on the map by calling the for loop and if we the passed param has already been created then we return out of the function and do nothing, else we create the marker and push it onto the global markers array. After the marker is created we then attach an info window with it's associated marker by doing markers[markers.length-1]['infowin'] markers.length-1 is just basically getting the newly pushed marker on the array. Within the info window we set the content using html. This is basically the information you put into the bubble or info window (it can be weather information which you can populate using a weather API and etc). After info window is attached we then attach an onclick event listener using the Google Map API's addListener and when the marker is clicked we want to open the info window that is associated with it by calling this['infowin'].open(map, this) where the map is our global map and this is the marker we are currently associating the onclick event with.
function addMarker(myloc) {
var current;
if (myloc == 'usa') current = usa;
else if (myloc == 'brasil') current = brasil;
else if (myloc == 'argentina') current = argentina;
for (var i = 0; i < markers.length; i++)
if (current.lat() === markers[i].position.lat() && current.lng() === markers[i].position.lng()) return;
markers.push(new google.maps.Marker({
map: map,
position: current,
title: myloc
}));
markers[markers.length - 1]['infowin'] = new google.maps.InfoWindow({
content: '<div>This is a marker in ' + myloc + '</div>'
});
google.maps.event.addListener(markers[markers.length - 1], 'click', function() {
this['infowin'].open(map, this);
});
}
When all is done we basically attach window.onload event and call the initialize function:
window.onload = initialize;

Categories

Resources