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

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);
}
}

Related

Dynamically create a Google Maps API V3 Script function

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>

How to find accurate LatLng values of google map

In my App,user can find place Name using click event,after getting place Name,I am showing the place name to user with inputFieldFor this I written the following code.
//helper function
function makingGeocodeRequest(obj,callback){
var geocodeInstance=new google.maps.Geocoder();
geocodeInstance.geocode(obj,callback);
}
google.maps.event.addListener(mapInstane,"click",function(event){
makingGeocodeRequest(_.object(["location"],[event.latLng]),
function(res,status){
document.getElementById("field").value=res[0]["formatted_address"];
}
)
})
Once user click on Save button.I am finding latlng value based on place Name.using the following code
makingGeocodeRequest(
_.object(["address"],[document.getElementById("field").value]),
function(res,status){
if (status===google.maps.GeocoderStatus.OK) {
var latLngObj=res[0]["geometry"]["location"];
console.log(latLngObj;
}
}
)
The problem here,both latlng values are different(click event time latlng value and save button action latlng value).
Actually both are finding from Google,but it's returning different latlng values.
While click event event,I am changing cursor style with this Icon.After click on Save button reverting default cursor.
How can I fix this.Can anyone help me.
Thanks.
To solve your problem you can create and array of points, add marker to this array and render results of the array on the map.
Here is how you can do this :
With Javascript,
<script type="text/javascript">
var map;
var markersList= [];
function initGMap()
{
var latlng = new google.maps.LatLng(39, 20);
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), myOptions);
// add a click event handler to the map object and get the lat Lng and then place it on the map
google.maps.event.addListener(map, "click", function(event)
{
// place a marker
placeMarker(event.latLng);
// display the lat/lng in your form's lat/lng fields
document.getElementById("latVal").value = event.latLng.lat();
document.getElementById("lngVal").value = event.latLng.lng();
});
}
// here is the function to place Marker on the map
function placeMarker(location) {
// first remove all markers if there are any
deleteOverlays();
var marker = new google.maps.Marker({
position: location,
map: map
});
// add marker in markers array
markersList.push(marker);
//map.setCenter(location);
}
// Here you can use this function to delete all markers in the array
function deleteOverlays() {
if (markersList) {
for (i in markersList) {
markersList[i].setMap(null);
}
markersList.length = 0;
}
}
</script>
With Html code,
<body onload="initGMap()">
<div id="map"></div>
<input type="text" id="latVal">
<input type="text" id="lngVal">
</body>

Uncaught TypeError: Cannot call method 'panTo' of undefined

I'm occasionally seeing a javascript error (Uncaught TypeError: Cannot call method 'panTo' of undefined) when loading my website. My website, for reference, is www.nolofo.com. What is supposed to happen when you load that page is to determine your location and move the map to that location. Sometimes this works just fine, other times it does not. I can't seem to figure out the pattern other than when it doesn't work I see this error message in the javascript log. Perhaps something is not being loaded in the correct order?
<script type="text/javascript">
// Check to see if this browser supports geolocation.
if (navigator.geolocation) {
// This is the location marker that we will be using on the map. Let's store a reference to it here so that it can be updated in several places.
var locationMarker = null;
var myLat = null;
var myLng = null;
// Get the location of the user's browser using the native geolocation service.
navigator.geolocation.getCurrentPosition(
function (position) {
// Check to see if there is already a location. There is a bug in FireFox where this gets invoked more than once with a cached result.
if (locationMarker){
return;
}
// Log that this is the initial position.
console.log( "Initial Position Found" );
// Assign coordinates to global variables
myLat = position.coords.latitude;
myLng = position.coords.longitude;
moveToLocation(myLat, myLng);
}
);
}
// Start the Google Maps implementation
var map;
var markersArray = [];
function initialize() {
var mapOptions = {
zoom: 13,
center: new google.maps.LatLng(40.760779, -111.891047),
mapTypeId: google.maps.MapTypeId.TERRAIN,
scaleControl: true
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
// Add all recent listing markers to map
<?php
foreach ($coordinateArray as $Key => $Value) {
$listingQuery = mysql_query("
SELECT
Listings.Lat,
Listings.Lng,
Listings.Title,
Listings.Type
FROM
Listings
WHERE
Listings.ID='$Key'
");
if (!$listingQuery) {
die('<p>Error executing query (2) with database!<br />'.
'Error: ' . mysql_error() . '</p>');
}
$listingArray = mysql_fetch_array($listingQuery);
$ListingLat = $listingArray["Lat"];
$ListingLng = $listingArray["Lng"];
$ListingTitle = addslashes($listingArray["Title"]);
$ListingType = $listingArray["Type"];
$ListingLatLng = $ListingLat . ", " . $ListingLng;
?>
// Marker
var myLatLng = new google.maps.LatLng(<?=$ListingLatLng?>);
var marker<?=$Key?> = new google.maps.Marker({
position: myLatLng,
map: map,
title: ""
});
iconFile = 'http://maps.google.com/mapfiles/ms/icons/<?=$Value?>-dot.png';
marker<?=$Key?>.setIcon(iconFile);
// Info Window
var infowindow<?=$Key?> = new google.maps.InfoWindow({
content: '<b><?=$ListingType?></b><br /><?=$ListingTitle?>'
});
google.maps.event.addListener(marker<?=$Key?>, 'click', function() {
infowindow<?=$Key?>.open(map, marker<?=$Key?>);
});
<?php } ?>
// Add a click event handler to the map object
google.maps.event.addListener(map, "click", function(event) {
// Place a marker
placeMarker(event.latLng, event.latLng.lat(), event.latLng.lng());
// Display the lat/lng in your form's lat/lng fields
//document.getElementById("lat").value = event.latLng.lat();
//document.getElementById("lng").value = event.latLng.lng();
});
// Add a click event handler to the marker object
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent("Your content here");
infowindow.open(map, this);
});
}
function placeMarker(location, lat, lng) {
// Remove all markers if there are any
deleteOverlays();
var marker = new google.maps.Marker({
position: location,
map: map
});
// Add marker in markers array
markersArray.push(marker);
var contentString = 'New Listing';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
infowindow.open(map,marker);
google.maps.event.addListener(infowindow, "closeclick", function() {
deleteOverlays(); // removes the marker
});
//map.setCenter(location);
}
// Deletes all markers in the array by removing references to them
function deleteOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
}
function moveToLocation(lat, lng) {
var center = new google.maps.LatLng(lat, lng);
map.panTo(center);
}
// The function to trigger the marker click, 'id' is the reference index to the 'markers' array.
function linkClick(id){
google.maps.event.trigger(markersArray[id], 'click');
}
google.maps.event.addDomListener(window, 'load', initialize);
Most likely it's because you're trying to pan the map before the map has been loaded. You run that initial geolocation script as soon as the page is loaded. Sounds like sometimes getCurrentPosition() is faster than the map load, sometimes it's not.
What you can do is run your geolocation stuff after map has been loaded. The very last line in your script is an event listener for when the map has been loaded - you can use it for other bits too.
Wrap the whole first part in a function:
function setupGeoLocator() {
// Check to see if this browser supports geolocation.
if (navigator.geolocation) {
// This is the location marker that we will be using on the map. Let's store a reference to it here so that it can be updated in several places.
var locationMarker = null;
var myLat = null;
var myLng = null;
// Get the location of the user's browser using the native geolocation service.
navigator.geolocation.getCurrentPosition(
function (position) {
// Check to see if there is already a location. There is a bug in FireFox where this gets invoked more than once with a cached result.
if (locationMarker){
return;
}
// Log that this is the initial position.
console.log( "Initial Position Found" );
// Assign coordinates to global variables
myLat = position.coords.latitude;
myLng = position.coords.longitude;
moveToLocation(myLat, myLng);
}
);
}
}
And then call it when the 'load' event fires on the map.
google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addDomListener(window, 'load', setupGeoLocator);

google maps API3 drawing custom map icon based on user selection

Im working on a google maps plugin (there's always room for another right?) and I'm drawing a preview of the map my users will be inserting into their content. Im able to draw everything I set out to, custom content in the info window, setting the location (through places.Autocomplete) etc. The one thing that is escaping me is custom map icon isn't being drawn.
My goal is to have the default icon drawn on first load, and then update it when it changes
Im not getting any 404 or errors in the console, and I've checked my event handlers and they are all working. Can anyone tell me where I've going astray?
Here is what I have so far:
//Initilize the map
google.maps.event.addDomListener(window, 'load', initialize);
function initialize(infowindow) {
var init_center = new google.maps.LatLng(43.703793, -72.326187);
mapOptions = {
center: init_center,
zoom: parseFloat(mapZoomReturn),
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel : false,
};
var input = document.getElementById('mapAddress');
var autocomplete = new google.maps.places.Autocomplete(input);
var infowindow = new google.maps.InfoWindow();
//var marker = new google.maps.Marker({
// position: init_center,
// map: map,
// icon: mapMarkerImageReturn
//});
// Draw the map
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
// marker needs to be set after the map
var marker = new google.maps.Marker({
position: init_center,
map: map,
icon: mapMarkerImageReturn
});
// Set up event listeners
// Info window DOM->MAP
google.maps.event.addDomListener(document.getElementById('mapInfoWindow'),
'change', function() {
mapInfoWindowReturn = escape(jQuery('#mapInfoWindow').val());
// get the extra content from feild, by this time the place_changed even will have fired at least once, so we have these values
infowindowPlace = get_info_bubble(locIcon, locName, locAddress, locPhone, locWeb, mapInfoWindowReturn); // returns formatted markup for info bubble
infowindow.setContent(infowindowPlace);
});
// Marker dropdown selection DOM->MAP
google.maps.event.addDomListener(document.getElementById('mapMarker'), 'change', update_maker);
// Custom marker text field DOM->MAP
google.maps.event.addDomListener(document.getElementById('mapMarkerImage'), 'change', update_maker );
function update_maker(){
//update the marker imge - (not working)
markerImage = get_marker_image(); // returns URL as string
marker.setIcon(markerImage);
marker.setPosition(locPlace.geometry.location);
marker.setMap(map);
}
google.maps.event.addListener(autocomplete, 'place_changed', function() {
infowindowPlace = get_info_bubble(locIcon, locName, locAddress, locPhone, locWeb, mapInfoWindowReturn);
infowindow.close();
if (mapMarkerImageReturn !=='' || mapMarkerImageReturn !== false) marker.setVisible(false);
input.className = '';
locPlace = autocomplete.getPlace();
if (!locPlace.geometry) {
// Inform the user that the place was not found and return.
input.className = 'notfound';
return;
}
// If the place has a geometry, then present it on a map.
if (locPlace.geometry.viewport) {
map.fitBounds(locPlace.geometry.viewport);
mapCurrCenter = map.getCenter();
} else {
map.setCenter(locPlace.geometry.location);
map.setZoom(parseFloat(mapZoomReturn));
mapCurrCenter = map.getCenter();
}
// Set the marker image (not working)
markerImage = get_marker_image(); // returns URL as string
marker.setIcon(markerImage);
marker.setPosition(locPlace.geometry.location);
marker.setMap(map);
// get the location values for the info bubble
if (locPlace.address_components) {
//console.log(locPlace.address_components);
// Populate values for info bubble
locName = locPlace.name;
locIcon = locPlace.icon;
locAddress = locPlace.formatted_address;
locPhone = locPlace.formatted_phone_number;
locWeb = locPlace.website;
}
infowindowPlace = get_info_bubble(locIcon, locName, locAddress, locPhone, locWeb, mapInfoWindowReturn);
infowindow.setContent(infowindowPlace);
infowindow.open(map, marker);
});
}

Problem with my click event on GoogleMaps integration - Pulling data from a JSON file

I have GoogleMaps integrated into my site. I'm having a problem pulling my info from my JSON file into the Info Window when the markers are clicked.
Below is my current code:
/*********** Custom GoogleMaps functions ***********/
if (document.getElementById("events-map")) {
// set json path
var markerFile = '/scripts/json/find-events.json';
// set default map properties
var defaultLatlng = new google.maps.LatLng(41.4925, -99.9018);
// zoom level of the map
var defaultZoom = 4;
// variable for map
var map;
// variable for marker info window
var infowindow;
// List with all marker to check if exist
var markerList = {};
// option for google map object
var myOptions = {
zoom: defaultZoom,
center: defaultLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
/**
* Load Map
*/
function loadMap() {
// create new map make sure a DIV with id myMap exist on page
map = new google.maps.Map(document.getElementById("events-map"), myOptions);
// create new info window for marker detail pop-up
infowindow = new google.maps.InfoWindow();
// load markers
loadMarkers();
}
/**
* Load markers via ajax request from server
*/
function loadMarkers() {
// load marker jSon data
$.getJSON(markerFile, function(data) {
// loop all the markers
$.each(data, function(i, item) {
// add marker to map
loadMarker(item);
});
});
}
/**
* Load marker to map
*/
function loadMarker(makerData) {
// create new marker location
var myLatlng = new google.maps.LatLng(markerData['xCoordinate'], markerData['yCoordinate']);
// create new marker
var marker = new google.maps.Marker({
id: markerData['id'],
map: map,
title: markerData['propertyName'] ,
position: myLatlng
});
// add marker to list used later to get content and additional marker information
markerList[marker.id] = marker;
// add event listener when marker is clicked
// currently the marker data contain a dataurl field this can of course be done different
google.maps.event.addListener(marker, 'click', function() {
// show marker when clicked
showMarker(marker.id);
});
// add event when marker window is closed to reset map location
google.maps.event.addListener(infowindow, 'closeclick', function() {
map.setCenter(defaultLatlng);
map.setZoom(defaultZoom);
});
}
/**
* Show marker info window
*/
function showMarker(markerId) {
// get marker information from marker list
var marker = markerList[markerId];
// check if marker was found
if (marker) {
// get marker detail information from server
$.getJSON(markerFile, function(data) {
// show marker window
infowindow.setContent(data);
infowindow.open(map, marker);
});
} else {
alert('Error marker not found: ' + markerId);
}
}
google.maps.event.addDomListener(window, 'load', loadMap);
}
And here is the info that is contained in my JSON file:
{
"markers":[
{
"id":"1",
"xCoordinate" : 34.048928,
"yCoordinate" : -111.093731,
"propertyName" : "Arizona",
"propertyState" : "AZ",
"propertyPhone" : "777.777.7777",
"propertyEmail" : "test#example.com"
},
{
"id":"2",
"xCoordinate" : 38.582526,
"yCoordinate" : -92.510376,
"propertyName" : "Missouri",
"propertyState" : "MO",
"propertyPhone" : "777.777.7777",
"propertyEmail" : "test#example.com"
}
]
}
In
var marker = ...
$.getJSON(markerFile, function(data) {...marker...}
the function(data) is the callback that is called asynchronously when the result of the respective AJAX call is returned. At that moment the local variable marker is no longer in scope. You should apply a closure over the marker:
$.getJSON(markerFile, function(mapMarker) {
var m = mapMarker; // save the current marker in the closure
return function(data) { // return the required callback ...
// show marker window
infowindow.setContent(data);
infowindow.open(map, m);
} (marker) // ... applied to marker
});
There is a typo in your loadMarker function:
makerData should be markerData

Categories

Resources