Suggestion box only displays , , - javascript

I am making a mashup website that involves a map, and a search textbox in javascript. So as the title says, no matter what is inputted into the search box, only 2 commas appear in the suggestion box and when the suggestion is clicked on, it turn the map gray and unusable. Whats the problem? This is my javascript file, the function where this is located is in the configure function
// Google Map
var map;
// markers for map
var markers = [];
// info window
var info = new google.maps.InfoWindow();
// execute when the DOM is fully loaded
$(function() {
// styles for map
// https://developers.google.com/maps/documentation/javascript/styling
var styles = [
// hide Google's labels
{
featureType: "all",
elementType: "labels",
stylers: [
{visibility: "off"}
]
},
// hide roads
{
featureType: "road",
elementType: "geometry",
stylers: [
{visibility: "off"}
]
}
];
// options for map
// https://developers.google.com/maps/documentation/javascript/reference#MapOptions
var options = {
center: {lat: 35.7640, lng: -78.7786}, // Cary, North Carolina
disableDefaultUI: true,
mapTypeId: google.maps.MapTypeId.ROADMAP,
maxZoom: 14,
panControl: true,
styles: styles,
zoom: 13,
zoomControl: true
};
// get DOM node in which map will be instantiated
var canvas = $("#map-canvas").get(0);
// instantiate map
map = new google.maps.Map(canvas, options);
// configure UI once Google Map is idle (i.e., loaded)
google.maps.event.addListenerOnce(map, "idle", configure);
});
/**
* Adds marker for place to map.
*/
function addMarker(place)
{
var url = "/search?q=" + place;
$.getJSON(url, function(data){
var location = data.latitude + data.longitude;
mark = new google.maps.marker(location, map);
markers[0] = mark;
});
}
/**
* Configures application.
*/
function configure()
{
// update UI after map has been dragged
google.maps.event.addListener(map, "dragend", function() {
// if info window isn't open
// http://stackoverflow.com/a/12410385
if (!info.getMap || !info.getMap())
{
update();
}
});
// update UI after zoom level changes
google.maps.event.addListener(map, "zoom_changed", function() {
update();
});
// configure typeahead
$("#q").typeahead({
highlight: false,
minLength: 1
},
{
display: function(suggestion) { return null; },
limit: 10,
source: search,
templates: {
suggestion: Handlebars.compile(
"<div>" +
"<p>{{ place_name }}, {{ admin_name1 }}, {{ postal_code }}</p>" +
"</div>"
)
}
});
// re-center map after place is selected from drop-down
$("#q").on("typeahead:selected", function(eventObject, suggestion, name) {
// set map's center
map.setCenter({lat: parseFloat(suggestion.latitude), lng: parseFloat(suggestion.longitude)});
// update UI
update();
});
// hide info window when text box has focus
$("#q").focus(function(eventData) {
info.close();
});
// re-enable ctrl- and right-clicking (and thus Inspect Element) on Google Map
// https://chrome.google.com/webstore/detail/allow-right-click/hompjdfbfmmmgflfjdlnkohcplmboaeo?hl=en
document.addEventListener("contextmenu", function(event) {
event.returnValue = true;
event.stopPropagation && event.stopPropagation();
event.cancelBubble && event.cancelBubble();
}, true);
// update UI
update();
// give focus to text box
$("#q").focus();
}
/**
* Removes markers from map.
*/
function removeMarkers()
{
// TODO
}
/**
* Searches database for typeahead's suggestions.
*/
function search(query, syncResults, asyncResults)
{
// get places matching query (asynchronously)
var parameters = {
q: query
};
$.getJSON(Flask.url_for("search"), parameters)
.done(function(data, textStatus, jqXHR) {
// call typeahead's callback with search results (i.e., places)
asyncResults(data);
})
.fail(function(jqXHR, textStatus, errorThrown) {
// log error to browser's console
console.log(errorThrown.toString());
// call typeahead's callback with no results
asyncResults([]);
});
}
/**
* Shows info window at marker with content.
*/
function showInfo(marker, content)
{
// start div
var div = "<div id='info'>";
if (typeof(content) == "undefined")
{
// http://www.ajaxload.info/
div += "<img alt='loading' src='/static/ajax-loader.gif'/>";
}
else
{
div += content;
}
// end div
div += "</div>";
// set info window's content
info.setContent(div);
// open info window (if not already open)
info.open(map, marker);
}
/**
* Updates UI's markers.
*/
function update()
{
// get map's bounds
var bounds = map.getBounds();
var ne = bounds.getNorthEast();
var sw = bounds.getSouthWest();
// get places within bounds (asynchronously)
var parameters = {
ne: ne.lat() + "," + ne.lng(),
q: $("#q").val(),
sw: sw.lat() + "," + sw.lng()
};
$.getJSON(Flask.url_for("update"), parameters)
.done(function(data, textStatus, jqXHR) {
// remove old markers from map
removeMarkers();
// add new markers to map
for (var i = 0; i < data.length; i++)
{
addMarker(data[i]);
}
})
.fail(function(jqXHR, textStatus, errorThrown) {
// log error to browser's console
console.log(errorThrown.toString());
});
};

Nvm, figured out that in my application.py, I should have put jsonify(value) instead of jsonify([value]).

Related

How to assign unique IDs to drawn GeoJson features and then remove them based on their ID?

I'm trying to assign a unique ID to each feature that gets drawn on this Google Map, and then use the rightclick event to remove the feature that gets clicked on. Currently all features get removed, which is a problem.
Once the feature is added to the collection, I try to assign the unique ID:
var uniqueID = function() {
return ++currentID;
}
dataLayer.addListener('addfeature', savePolygon, function(event) {
event.feature.setProperty('featureID', uniqueID);
});
Then on rightclick event, I want to remove the feature that gets clicked on. I assumed you would need to have unique IDs for this step, hence the prior step.
dataLayer.addListener('rightclick', function() {
dataLayer.forEach(function(feature) {
dataLayer.remove(feature);
localStorage.removeItem('geoData');
});
});
Full code below.
JS:
var map;
var currentID = 0;
var uniqueID = function() {
return ++currentID;
}
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: -34.397,
lng: 150.644
},
zoom: 4,
// only show roadmap type of map, and disable ability to switch to other type
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
});
map.data.setControls(['Polygon']);
map.data.setStyle({
editable: true,
draggable: true
});
bindDataLayerListeners(map.data);
//load saved data
loadPolygons(map);
}
// Apply listeners to refresh the GeoJson display on a given data layer.
function bindDataLayerListeners(dataLayer) {
dataLayer.addListener('addfeature', savePolygon, function(event) {
event.feature.setProperty('featureID', uniqueID);
});
dataLayer.addListener('rightclick', function() {
dataLayer.forEach(function(feature) {
dataLayer.remove(feature);
localStorage.removeItem('geoData');
});
});
dataLayer.addListener('setgeometry', savePolygon);
}
function loadPolygons(map) {
var data = JSON.parse(localStorage.getItem('geoData'));
map.data.forEach(function(f) {
map.data.remove(f);
});
map.data.addGeoJson(data)
}
function savePolygon() {
map.data.toGeoJson(function(json) {
localStorage.setItem('geoData', JSON.stringify(json));
});
}
initMap();
Original source: I built this example from a JSFiddle found in this thread.
your addfeature listener was wrong, as addListener takes only a single callback function, so you need to call e.feature.setProperty then savePolygon inside a single anonymous callback function
Note, you had event.feature.setProperty('featureID', uniqueID); - it needs to be event.feature.setProperty('featureID', uniqueID());
dataLayer.addListener('addfeature', function(event) {
event.feature.setProperty('featureID', uniqueID());
savePolygon(event);
});
Then, in the rightclick lsitener, you can simply get the geoData - filter out the clicked item, save the geoData and then dataLayer.remove(e.feature);
dataLayer.addListener('rightclick', function(e) {
var data = JSON.parse(localStorage.getItem('geoData'));
data.features = data.features.filter(function(feature) {
return feature.properties.featureID !== e.feature.getProperty('featureID');
});
localStorage.setItem('geoData', JSON.stringify(data));
dataLayer.remove(e.feature);
});
working fiddle

TypeError: this is undefined inside an ajax call and google app maps

I have an asp mvc project where the user is asked for geolocalization via google maps (API), so i had to use jquery 1.7.2 and save it's coordinates, but when i try to save them via ajax request i get this error on firebug and stops all the other code.
http://i47.photobucket.com/albums/f195/warbandit69/ErrorKambi1_zpsac3979f4.png
As you can see the error is very unacurte with it's description, and here is the function on jquery that makes that call
function ReviewAtEnd() {
if (typeof (idserialF) != "undefined" && idserialF != null) {
var datax = { idjob: idjobx, latitud: Latitud, longitud: Longitud, coordinates: coordenadasGM };
var urlx = "/JOBS/PROG41/FailedItemOnSite";
$.ajax({
type: "POST",
url: urlx,
data: datax,
async: false,
success: function (data) {
mostrar_alert_ui(data.titulo, data.mensaje, 350);
if (data.success) {
AfterPassedTest();
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Failed " + urlx);
alert(xhr.responseText);
alert(thrownError);
}
});
}
}
UPDATE
Here is the google maps function i missed to show you
var Latitud;
var Longitud;
var coordenadasGM;
function showMap() {
//If HTML5 Geolocation Is Supported In This Browser
if (navigator.geolocation) {
//Use HTML5 Geolocation API To Get Current Position
navigator.geolocation.getCurrentPosition(function (position) {
//Get Latitude From Geolocation API
var latitude = position.coords.latitude;
Latitud = latitude;
//Get Longitude From Geolocation API
var longitude = position.coords.longitude;
Longitud = Longitud;
//Define New Google Map With Lat / Lon
var coords = new google.maps.LatLng(latitude, longitude);
coordenadasGM = coords;
//Specify Google Map Options
var mapOptions = {
zoom: 15,
center: coords,
mapTypeControl: true,
navigationControlOptions: { style: google.maps.NavigationControlStyle.SMALL }, mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("mapContainer"), mapOptions);
var marker = new google.maps.Marker({
position: coords,
map: map,
title: "You Are Here!"
});
}
);
} else {
//Otherwise - Gracefully Fall Back If Not Supported... Probably Best Not To Use A JS Alert Though :)
mostrar_alert_ui("WARNING", "Geolocation API is not supported in your browser.", 350)
}
}
//Once Page Is Populated - Initiate jQuery
$(document).ready(function () {
//Show The Map
showMap();
// When The Viewing Window Is Resized
$(window).resize(function () {
//CSS Resizes Container So Lets Recall The Map Function
showMap();
});
});
Jsfiddle here -> http://jsfiddle.net/ricardojriosr/9mzss1ud/

IndexedDB error: Uncaught DataCloneError: Failed to execute 'put' on 'IDBObjectStore': An object could not be cloned

I am using the Google maps API along with the HTML 5 geolocation API to display my position as a marker on a map. Once this marker is displayed I have a simple on marker double-click function that saves a new marker to my current position using indexedDB. Everything goes well until the Object is about to be stored, then I received the message "Uncaught DataCloneError: Failed to execute 'put' on 'IDBObjectStore': An object could not be cloned." in the console. my code is as follows:
function initialize() {
var mapProperties = { // Set the maps properties
center: new google.maps.LatLng(55.8580, -4.2590),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-overview"), mapProperties); //Display the map in the map-overview div
function NogeoLocation(e) { //A function to handle users that do not have Geolocation
if (e) {
var content = 'Error: Unfortunately the Geolocation service failed.';
} else {
var content = 'Error: Sorry, Your web browser doesn\'t support geolocation.';
}
var options = { //Error options
map: map,
position: new google.maps.LatLng(60, 105), //Set new position on Error
content: content //Display error message
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
//Using HTML5 Geolocation
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var position = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var contentString = "Here is your current location!" + "<button onclick='myBtn()'>Save</button>"
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var marker = new google.maps.Marker({
position: position,
map: map,
title: 'My House'
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.open(map, marker);
});
var db;
function indexedDBOk() {
return "indexedDB" in window;
}
google.maps.event.addListener(marker, 'dblclick', function () {
alert("dbl Click");
console.log(position);
if (!indexedDBOk) return;
var openRequest = indexedDB.open("idarticle_people", 1);
openRequest.onupgradeneeded = function (e) {
var thisDB = e.target.result;
if (!thisDB.objectStoreNames.contains("people")) {
thisDB.createObjectStore("people");
}
}
openRequest.onsuccess = function (e) {
console.log("running onsuccess");
db = e.target.result;
var transaction = db.transaction(["people"], "readwrite");
var store = transaction.objectStore("people");
//Define a marker
var marker = {
position: position,
map: map,
title: 'New Marker'
}
console.log(marker);
console.log("about to perform add");
//Perform the add
var request = store.put(marker, 1);
console.log("added");
request.onerror = function (e) {
console.log("Error", e.target.error.name);
//some type of error handler
}
request.onsuccess = function (e) {
console.log("Woot! Did it");
}
}
openRequest.onerror = function (e) {
//Do something for the error
}
});
map.setCenter(position);
}, function () {
NogeoLocation(true); // Refers to NogeoLocation function
});
} else {
// If the user's browser doesn't support Geolocation
NogeoLocation(false);
} //End of HTML5 GeoLocation
} // End of the function that initializes Google Maps
google.maps.event.addDomListener(window, 'load', initialize); //On page load, execute initialize()
marker can't be cloned because the object stored in the map-property contains a reference to a DOMNode(#map-overview), which can't be cloned (see:Things that don't work with structured clones).
Remove the map-property, it will not be re-usable at all because the google.maps.Map-instance will not exist when you retrieve the marker later.
I discovered that the reason for the error was to try to add an object that was not recognized to a cache.
this.storage.set ("page", HomePage);
I switched to a string and it worked
this.storage.set ("page", "HomePage");

Automatically fill up the Google Map search bar (Address Picker)

I want to present my users with a text box wherein they can type in their address. As they type their address, there's a new window will open (Google map) and automatically fill up the search box in Google map. I want to provide the users with suggestions/predictions of what address they are trying to type. I'm also concerned about the relevance of this address (e.g. that the address is not an address halfway across the world).
How to automatically fill the search box in Google map from the inputted address text box from another website?
E.g In my website, there's a text box and I input an address in that text box and when I click enter in that text box there's a new window appear and display the Google Map with search bar (in that search bar, the address is already there)
Is this possible in javascript and jquery? Please help me. I'm newbie in those PL. Thank you
Here's the code:
(function($, window, document, undefined){
var defaults = {
bounds: true,
country: null,
map: false,
details: false,
detailsAttribute: "name",
autoselect: true,
location: false,
mapOptions: {
zoom: 14,
scrollwheel: false,
mapTypeId: "roadmap"
},
markerOptions: {
draggable: false
},
maxZoom: 16,
types: ['geocode'],
blur: false
};
var componentTypes = ("street_address route intersection political " +
"country administrative_area_level_1 administrative_area_level_2 " +
"administrative_area_level_3 colloquial_area locality sublocality " +
"neighborhood premise subpremise postal_code natural_feature airport " +
"park point_of_interest post_box street_number floor room " +
"lat lng viewport location " +
"formatted_address location_type bounds").split(" ");
var placesDetails = ("id url website vicinity reference name rating " +
"international_phone_number icon formatted_phone_number").split(" ");
// The actual plugin constructor.
function GeoComplete(input, options) {
this.options = $.extend(true, {}, defaults, options);
this.input = input;
this.$input = $(input);
this._defaults = defaults;
this._name = 'geocomplete';
this.init();
}
// Initialize all parts of the plugin.
$.extend(GeoComplete.prototype, {
init: function(){
this.initMap();
this.initMarker();
this.initGeocoder();
this.initDetails();
this.initLocation();
},
// Initialize the map but only if the option `map` was set.
// This will create a `map` within the given container
// using the provided `mapOptions` or link to the existing map instance.
initMap: function(){
if (!this.options.map){ return; }
if (typeof this.options.map.setCenter == "function"){
this.map = this.options.map;
return;
}
this.map = new google.maps.Map(
$(this.options.map)[0],
this.options.mapOptions
);
// add click event listener on the map
google.maps.event.addListener(
this.map,
'click',
$.proxy(this.mapClicked, this)
);
google.maps.event.addListener(
this.map,
'zoom_changed',
$.proxy(this.mapZoomed, this)
);
},
// Add a marker with the provided `markerOptions` but only
// if the option was set. Additionally it listens for the `dragend` event
// to notify the plugin about changes.
initMarker: function(){
if (!this.map){ return; }
var options = $.extend(this.options.markerOptions, { map: this.map });
if (options.disabled){ return; }
this.marker = new google.maps.Marker(options);
google.maps.event.addListener(
this.marker,
'dragend',
$.proxy(this.markerDragged, this)
);
},
// Associate the input with the autocompleter and create a geocoder
// to fall back when the autocompleter does not return a value.
initGeocoder: function(){
var options = {
types: this.options.types,
bounds: this.options.bounds === true ? null : this.options.bounds,
componentRestrictions: this.options.componentRestrictions
};
if (this.options.country){
options.componentRestrictions = {country: this.options.country};
}
this.autocomplete = new google.maps.places.Autocomplete(
this.input, options
);
this.geocoder = new google.maps.Geocoder();
// Bind autocomplete to map bounds but only if there is a map
// and `options.bindToMap` is set to true.
if (this.map && this.options.bounds === true){
this.autocomplete.bindTo('bounds', this.map);
}
// Watch `place_changed` events on the autocomplete input field.
google.maps.event.addListener(
this.autocomplete,
'place_changed',
$.proxy(this.placeChanged, this)
);
// Prevent parent form from being submitted if user hit enter.
this.$input.keypress(function(event){
if (event.keyCode === 13){ return false; }
});
// Listen for "geocode" events and trigger find action.
this.$input.bind("geocode", $.proxy(function(){
this.find();
}, this));
// Trigger find action when input element is blured out.
// (Usefull for typing partial location and tabing to the next field
// or clicking somewhere else.)
if (this.options.blur === true){
this.$input.blur($.proxy(function(){
this.find();
}, this));
}
},
// Prepare a given DOM structure to be populated when we got some data.
// This will cycle through the list of component types and map the
// corresponding elements.
initDetails: function(){
if (!this.options.details){ return; }
var $details = $(this.options.details),
attribute = this.options.detailsAttribute,
details = {};
function setDetail(value){
details[value] = $details.find("[" + attribute + "=" + value + "]");
}
$.each(componentTypes, function(index, key){
setDetail(key);
setDetail(key + "_short");
});
$.each(placesDetails, function(index, key){
setDetail(key);
});
this.$details = $details;
this.details = details;
},
// Set the initial location of the plugin if the `location` options was set.
// This method will care about converting the value into the right format.
initLocation: function() {
var location = this.options.location, latLng;
if (!location) { return; }
if (typeof location == 'string') {
this.find(location);
return;
}
if (location instanceof Array) {
latLng = new google.maps.LatLng(location[0], location[1]);
}
if (location instanceof google.maps.LatLng){
latLng = location;
}
if (latLng){
if (this.map){ this.map.setCenter(latLng); }
if (this.marker){ this.marker.setPosition(latLng); }
}
},
// Look up a given address. If no `address` was specified it uses
// the current value of the input.
find: function(address){
this.geocode({
address: address || this.$input.val()
});
},
// Requests details about a given location.
// Additionally it will bias the requests to the provided bounds.
geocode: function(request){
if (this.options.bounds && !request.bounds){
if (this.options.bounds === true){
request.bounds = this.map && this.map.getBounds();
} else {
request.bounds = this.options.bounds;
}
}
if (this.options.country){
request.region = this.options.country;
}
this.geocoder.geocode(request, $.proxy(this.handleGeocode, this));
},
// Get the selected result. If no result is selected on the list, then get
// the first result from the list.
selectFirstResult: function() {
//$(".pac-container").hide();
var selected = '';
// Check if any result is selected.
if ($(".pac-item-selected")['0']) {
selected = '-selected';
}
// Get the first suggestion's text.
var $span1 = $(".pac-container .pac-item" + selected + ":first span:nth-child(2)").text();
var $span2 = $(".pac-container .pac-item" + selected + ":first span:nth-child(3)").text();
// Get the inputted address from LAP
var
// Adds the additional information, if available.
var firstResult = $span1;
if ($span2) {
firstResult += " - " + $span2;
}
this.$input.val(firstResult);
return firstResult;
},
// Handles the geocode response. If more than one results was found
// it triggers the "geocode:multiple" events. If there was an error
// the "geocode:error" event is fired.
handleGeocode: function(results, status){
if (status === google.maps.GeocoderStatus.OK) {
var result = results[0];
this.$input.val(result.formatted_address);
this.update(result);
if (results.length > 1){
this.trigger("geocode:multiple", results);
}
} else {
this.trigger("geocode:error", status);
}
},
// Triggers a given `event` with optional `arguments` on the input.
trigger: function(event, argument){
this.$input.trigger(event, [argument]);
},
// Set the map to a new center by passing a `geometry`.
// If the geometry has a viewport, the map zooms out to fit the bounds.
// Additionally it updates the marker position.
center: function(geometry){
if (geometry.viewport){
this.map.fitBounds(geometry.viewport);
if (this.map.getZoom() > this.options.maxZoom){
this.map.setZoom(this.options.maxZoom);
}
} else {
this.map.setZoom(this.options.maxZoom);
this.map.setCenter(geometry.location);
}
if (this.marker){
this.marker.setPosition(geometry.location);
this.marker.setAnimation(this.options.markerOptions.animation);
}
},
// Update the elements based on a single places or geoocoding response
// and trigger the "geocode:result" event on the input.
update: function(result){
if (this.map){
this.center(result.geometry);
}
if (this.$details){
this.fillDetails(result);
}
this.trigger("geocode:result", result);
},
// Populate the provided elements with new `result` data.
// This will lookup all elements that has an attribute with the given
// component type.
fillDetails: function(result){
var data = {},
geometry = result.geometry,
viewport = geometry.viewport,
bounds = geometry.bounds;
// Create a simplified version of the address components.
$.each(result.address_components, function(index, object){
var name = object.types[0];
data[name] = object.long_name;
data[name + "_short"] = object.short_name;
});
// Add properties of the places details.
$.each(placesDetails, function(index, key){
data[key] = result[key];
});
// Add infos about the address and geometry.
$.extend(data, {
formatted_address: result.formatted_address,
location_type: geometry.location_type || "PLACES",
viewport: viewport,
bounds: bounds,
location: geometry.location,
lat: geometry.location.lat(),
lng: geometry.location.lng()
});
// Set the values for all details.
$.each(this.details, $.proxy(function(key, $detail){
var value = data[key];
this.setDetail($detail, value);
}, this));
this.data = data;
},
// Assign a given `value` to a single `$element`.
// If the element is an input, the value is set, otherwise it updates
// the text content.
setDetail: function($element, value){
if (value === undefined){
value = "";
} else if (typeof value.toUrlValue == "function"){
value = value.toUrlValue();
}
if ($element.is(":input")){
$element.val(value);
} else {
$element.text(value);
}
},
// Fire the "geocode:dragged" event and pass the new position.
markerDragged: function(event){
this.trigger("geocode:dragged", event.latLng);
},
mapClicked: function(event) {
this.trigger("geocode:click", event.latLng);
},
mapZoomed: function(event) {
this.trigger("geocode:zoom", this.map.getZoom());
},
// Restore the old position of the marker to the last now location.
resetMarker: function(){
this.marker.setPosition(this.data.location);
this.setDetail(this.details.lat, this.data.location.lat());
this.setDetail(this.details.lng, this.data.location.lng());
},
// Update the plugin after the user has selected an autocomplete entry.
// If the place has no geometry it passes it to the geocoder.
placeChanged: function(){
var place = this.autocomplete.getPlace();
if (!place || !place.geometry){
if (this.options.autoselect) {
// Automatically selects the highlighted item or the first item from the
// suggestions list.
var autoSelection = this.selectFirstResult();
this.find(autoSelection);
}
} else {
// Use the input text if it already gives geometry.
this.update(place);
}
}
});
// A plugin wrapper around the constructor.
// Pass `options` with all settings that are different from the default.
// The attribute is used to prevent multiple instantiations of the plugin.
$.fn.geocomplete = function(options) {
var attribute = 'plugin_geocomplete';
// If you call `.geocomplete()` with a string as the first parameter
// it returns the corresponding property or calls the method with the
// following arguments.
if (typeof options == "string"){
var instance = $(this).data(attribute) || $(this).geocomplete().data(attribute),
prop = instance[options];
if (typeof prop == "function"){
prop.apply(instance, Array.prototype.slice.call(arguments, 1));
return $(this);
} else {
if (arguments.length == 2){
prop = arguments[1];
}
return prop;
}
} else {
return this.each(function() {
// Prevent against multiple instantiations.
var instance = $.data(this, attribute);
if (!instance) {
instance = new GeoComplete( this, options );
$.data(this, attribute, instance);
}
});
}
};
})( jQuery, window, document );
AFIK, the search bar which is used in Google maps search api is a simple textbox (input type="text") and its id is pac-input
$('#pac-input').val($('your address element').val()); //copy the value
$('#pac-input').focus(); //focus might trigger automatically
JSfiddle
Read document for geocoder = new google.maps.Geocoder();
and try this:
var input_address = $('your address element').val();
geocoder.geocode({address: input_address}, reverseGeocodeResult);
function reverseGeocodeResult(results, status) {
currentReverseGeocodeResponse = results;
if (status == 'OK') {
if (results.length == 0) {
document.getElementById('cong_viec_dia_chi').innerHTML = 'None';
} else {
document.getElementById('cong_viec_dia_chi').innerHTML = results[0].formatted_address;
}
} else {
document.getElementById('cong_viec_dia_chi').innerHTML = 'can't get address';
}
}
Update: demo here
http://jsfiddle.net/HoangHieu/x8dSP/3626/
http://jsfiddle.net/HoangHieu/x8dSP/3631/

Geocode Javascript problem

I wonder whether someone may be able to help me please.
Because of loading issues, I've moved the map options code to my HTML form, rather than it being in a separate Javascript file.
The problem is that I now can't get the Geocode functionality to work. I've added my code below. I'm sure it must be something simple, but I'm a little perplexed by this. I just wondered whether it would be at all possible please that someone could let me know where I've gone wrong.
Many thanks
function geocode() {
// This is defining the global variables
var geocoder, marker;
// This is making the link with the 'Search For Location' HTML form
var form = document.getElementById('searchforlocationform');
// This is catching the forms submit event
form.onsubmit = function() {
// This is getting the Address from the HTML forms 'Address' text box
var address = document.getElementById('inputaddress').value;
// This is making the Geocoder call
getCoordinates(address);
// This is preventing the form from doing a page submit
return false;
}
}
function geocodePosition(pos) {
geocoder.geocode({
latLng: pos
},
function(responses) {
if (responses && responses.length > 0) {
updateMarkerAddress(responses[0].formatted_address);
} else {
updateMarkerAddress('Cannot determine address at this location.');
}
});
}
//New Code
function updateMarkerStatus(str) {
document.getElementById('markerStatus').innerHTML = str;
}
//Changed 'address' to 'returnedaddress'
function updateMarkerAddress(str) {
document.getElementById('returnedaddress').value= str;
}
// This creates the function that will return the coordinates for the address
function getCoordinates(address) {
// This checks to see if there is already a geocoded object. If not, it creates one
if(!geocoder){geocoder = new google.maps.Geocoder();}
// This is creating a GeocoderRequest object
var geocoderRequest = {address: address}
// This is making the Geocode request
geocoder.geocode(geocoderRequest, function(results, status) {
// Check if status is OK before proceeding
if (status == google.maps.GeocoderStatus.OK) {
// Center the map on the returned location
map.setCenter(results[0].geometry.location);
// Check to see if we've already got a Marker object
if (!marker) {
map.setZoom(16);
marker = new google.maps.Marker({
map: map, draggable:true
});
}
// Setting the position of the marker to the returned location
marker.setPosition(results[0].geometry.location);
// Add dragging event listeners.
google.maps.event.addListener(marker, function() {
updateMarkerAddress;
});
//This fills out the 'Latitude' and 'Longitude' text boxes on the HTML form
document.getElementById('osgb36lat').value= results[0].geometry.location.lat();
document.getElementById('osgb36lon').value= results[0].geometry.location.lng();
//This allows the marker to be draggable and tells the 'Latitude' and 'Longitude' text boxes on the HTML form to update with the new co-ordinates as the marker is dragged
google.maps.event.addListener(marker,'dragend',
function() {
updateMarkerStatus;
geocodePosition(marker.getPosition());
document.getElementById('osgb36lat').value = marker.position.lat();
document.getElementById('osgb36lon').value = marker.position.lng();
});
// Update current position info.
latLng = [marker.position.lat(), marker.position.lng()].join(', ');
geocodePosition(marker.getPosition());
var point = marker.getPosition();
map.panTo(point);
}
}
)
}
<script type="text/javascript">
(function() {
window.onload = function(){
var latlng = new google.maps.LatLng(54.312195845815246,-4.45948481875007);
var options = {
zoom: 6,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
position: google.maps.ControlPosition.TOP_RIGHT
},
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.ZOOM_PAN,
position: google.maps.ControlPosition.TOP_LEFT
},
scaleControl: true,
scaleControlOptions: {
position: google.maps.ControlPosition.BOTTOM_LEFT
}
};
var map = new google.maps.Map(document.getElementById('map'), options);
}
})();
</script>
You seen to be trying to call updateMarkerAddress with updateMarkerAddress; and updateMarkerStatus with updateMarkerStatus;, here you are missing (/*some param*/).
What are the loading issues? Maybe if you show your html someone could help with that too.

Categories