XML submitted just fine to Amazon MWS but price not being updated - django

I created my own repricer of sorts but the price isn't being updated on Amazon's side.
My code seems to work just fine based off the response from Amazon after submitting it. I'm hoping someone here knows more about why its not actually updating the price.
Here's the XML submitted:
<?xml version="1.0" encoding="utf-8" ?>
<AmazonEnvelope
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="amzn-envelope.xsd">
<Header>
<DocumentVersion>1.01</DocumentVersion>
<MerchantIdentifier>MERCHANTID</MerchantIdentifier>
</Header>
<MessageType>Price</MessageType>
<Message>
<MessageID>1</MessageID>
<Price>
<SKU>mysku</SKU>
<StandardPrice currency="USD">350.50</StandardPrice>
</Price>
</Message>
</AmazonEnvelope>
Heres the response:
GetFeedSubmissionResultResponse{}(ResponseMetadata: <Element_?/ResponseMetadata_0x7fee61f74248>, GetFeedSubmissionResultResult: <Element_?/GetFeedSubmissionResultResult_0x7fee61f74248>, AmazonEnvelope:
{'xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance', 'xsi:noNamespaceSchemaLocation': 'amzn-envelope.xsd'}, DocumentVersion: '1.02', MerchantIdentifier: 'M_EXAMPLE_1234', Header: '\n\t', MessageType: 'ProcessingReport', MessageID: '1', DocumentTransactionID: '4200000000', StatusCode: 'Complete', MessagesProcessed: '1', MessagesSuccessful: '1', MessagesWithError: '0', MessagesWithWarning: '0', ProcessingSummary: '\n\t\t\t', ProcessingReport: '\n\t\t', Message: '\n\t')
I don't know if showing my code will help in this instance since I get a successful response from Amazon. Here it is regardless:
...
# Provide credentials.
conn = MWSConnection(
aws_access_key_id=AWS_ACCESS_KEY_ID,
aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
Merchant=AMZ_SELLER_ID
)
# Get the service resource
sqs = boto3.resource('sqs')
# Get the queue
queue = sqs.get_queue_by_name(QueueName=SQS_QUEUE_NAME)
for index, message in enumerate(queue.receive_messages(MaxNumberOfMessages=10)):
...
import time
from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('repricer', 'xml_templates'), trim_blocks=True, lstrip_blocks=True)
template = env.get_template('_POST_PRODUCT_PRICING_DATA_.xml')
class Message(object):
def __init__(self, s, price):
self.SKU = s
self.PRICE = round(price, 2)
self.CURRENCY = USD_CURRENCY
feed_messages = [
Message(sku.sku, new_price),
]
namespace = dict(MerchantId=AMZ_SELLER_ID, FeedMessages=feed_messages)
feed_content = template.render(namespace).encode('utf-8')
print(feed_content)
feed = conn.submit_feed(
FeedType='_POST_PRODUCT_PRICING_DATA_',
PurgeAndReplace=False,
MarketplaceIdList=[MARKETPLACE_ID],
content_type='text/xml',
FeedContent=feed_content
)
feed_info = feed.SubmitFeedResult.FeedSubmissionInfo
print('Submitted product feed: ' + str(feed_info))
while True:
submission_list = conn.get_feed_submission_list(
FeedSubmissionIdList=[feed_info.FeedSubmissionId]
)
info = submission_list.GetFeedSubmissionListResult.FeedSubmissionInfo[0]
submission_id = info.FeedSubmissionId
status = info.FeedProcessingStatus
print('Submission Id: {}. Current status: {}'.format(submission_id, status))
if status in ('_SUBMITTED_', '_IN_PROGRESS_', '_UNCONFIRMED_'):
print('Sleeping and check again....')
time.sleep(60)
elif status == '_DONE_':
feedResult = conn.get_feed_submission_result(FeedSubmissionId=submission_id)
print(feedResult)
break
else:
print("Submission processing error. Quit.")
break

There are a couple of possible reasons, listed roughly in the order of likelihood:
1. Amazon is slower to update values than they say they are. It is possible that although the feed was successful, there is still a period of time before that change reflects on Amazon (even changing values from SellerCentral comes with a messages that it isn't instant).
Wait a few minutes and see if the change eventually shows up.
2. You could have an alternate repricing service still active. If you are currently using another repricer for this SKU, it might be competing with your attempts and reverting the price based on its own ruleset.
It's possible to use the GetFeedSubmissionList call to see if another _POST_PRODUCT_PRICING_DATA_ feed was submitted after yours (though with no way to view the submitted contents).
3. There might be a conflict with the min and max prices on the SKU (whether you set them or not), and the price you tried to set is outside of the allowed range. This is a result of one of Amazon's policies requiring new and updated SKU's to have those set or it uses a default criteria.
In our continued effort to reduce price error risks to sellers and to avoid potentially negative customer experiences, starting on January 14, 2015, you will not be able to use your Seller Central preferences to select a blanket “opt-out” from all potential low- and high-pricing error rules. Instead, you will need to set a minimum and maximum allowed selling price for each product in your inventory if you do not want Amazon’s default potential pricing error rules to apply to that product.
I can't find an announcement page on this so it may have been an email, but it is quoted as such on the forums
Under those circumstances the feed will report back successful (because its references/format are correct), but the price change will silently fail because of the price range limits that are set.
You can verify if this is your issue by viewing the SKU under SellerCentral Manage Inventory page. You may have to turn on the min/max columns to view current values depending on your preferences set for that page.
Unfortunately, there is no way to pull min/max prices on inventory items to know if this will be an issue ahead of time:
Dear Seller,
I am Sharon from Amazon Seller Support and I will be assisting you with your concern today.
From the content of your email, I understand that you are concerned if there's any report where you can download the report for 'Minimum Price' and 'Maximum Price'.
I regret to inform you that as of now the reports which are available will only provide information for 'standard_price' and 'list_price'.
I understand that this is a disappointment for you but please understand that as of not this feature of including 'Minimum Price' and 'Maximum Price' in the inventory reports has not been included and I sincerely apologize for all the inconvenience caused to you in this regard.
via support ticket to Amazon MWS team, Jul 03, 2016
4. It could be possible Amazon does not allow the feed to update a price during an active promotion. You should be able to check if an item is on sale by viewing the SellerCentral Manage Inventory page, where the "price" column would be bordered in green.
Seems unlikely as they require the "StandardPrice" element to be provided with the "Sale" element, but Amazon's own "Automate Pricing" tool lists it as a possible reason for the tool failing.
5. You are applying the price update to the wrong marketplace.
If the id provided to the call under MarketplaceIdList=[MARKETPLACE_ID], is for a different marketplace than the one you are checking, you won't see the price change.
Amazon does fail the feed submission request if you submit to a marketplace you do not have access to, so this may not be the issue if you only have one marketplace.
6. You are looking for the new price in the wrong spot.
If you are looking under the SellerCentral Manage Inventory page, make sure you are looking at the "Price" column and not the "Lowest Price" column.
If you are looking at the product's detail or offer page (on Amazon's storefront), make sure you are looking at your offer. You may not be the main offer shown on the detail page or the top offer shown on the offer listing page.
And of course, make sure you have the right SKU / ASIN.
7. This is for a different feed, but a user has reported that Amazon just doesn't update information sometimes, requiring the feed to be resent.
There is an alternate feed you can try using to update price information _POST_FLAT_FILE_INVLOADER_DATA_, but it is a flat file type (tab delimited) so your XML schema would not transfer over. Probably only worth trying if you think the issue is related to the specific feed you're using.

I don't know Python but your XML looks ok, here is my PHP code which I use to do price change for last 5 years and it works fine. I don't know if this helps you as it's PHP.
$feed = <<< EOD
<?xml version="1.0" encoding="utf-8"?>
<AmazonEnvelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="amzn-envelope.xsd">
<Header>
<DocumentVersion>1.01</DocumentVersion>
<MerchantIdentifier>$merchant_token</MerchantIdentifier>
</Header>
<MessageType>Price</MessageType>
<Message>
<MessageID>1</MessageID>
<Price>
<SKU>$sku</SKU>
<StandardPrice currency="$currency">$new_price</StandardPrice>
</Price>
</Message>
</AmazonEnvelope>
EOD;
$feed = trim($feed);
$feedHandle = #fopen('php://temp', 'rw+');
fwrite($feedHandle, $feed);
rewind($feedHandle);
$parameters = array(
'Merchant' => $MERCHANT_ID,
'MarketplaceIdList' => $marketplaceIdArray,
'FeedType' => '_POST_PRODUCT_PRICING_DATA_',
'FeedContent' => $feedHandle,
'PurgeAndReplace' => false, //Leave this PurgeAndReplace to false so that it want replace whole product in amazon inventory
'ContentMd5' => base64_encode(md5(stream_get_contents($feedHandle), true))
);
rewind($feedHandle);
$request = new MarketplaceWebService_Model_SubmitFeedRequest($parameters);
$return_feed = invokeSubmitFeed($service, $request, $price_change_info_log);
fclose($feedHandle);

I ended up contacting Amazon api support and they found out that it takes up to 15 minutes for the price to change. Also I had another script that uploaded new products and updated the inventory & price for existing products...this script was competing with my repricing script.
I resolved the issue by changing how the second script updates price for existing products.

Related

Google Analytics Measurement Protocol can not track cart addition and product view

I have implemented a measurement protocol in my project. I can successfully track purchases, checkouts, pageviews and refunds.
For example, by sending this data with some additions from function outside I can track purchase events.
data = {
't': 'pageview',
'ti': '123123',
'tr': 1510,
'ts': 10,
'cu': 'GEL',
'pa': 'purchase',
'cid': request.COOKIES.get('client_id'),
'pr1id': '123123',
'pr1nm': 'iPhoneXR',
'pr1ca': 'Smartphones',
'pr1pr': 500,
'pr1br': 'Apple',
'pr1va': 'RED 128 GB',
'pr1qt': 2
}
Now I am struggling to track product views and cart additions and I have gone through whole measurement protocol parameters and common hits that was shown in the documentation but could not find a solution. Any ideas on how can I track cart additions and product views?
You have set Product Action with a value purchase. The other available value options are detail, click, add, remove, checkout, checkout_option and refund.
You may want to try add instead. I am referring to Google API documentation at https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#pa

Django razorpay: How to get the order id after payment is complete

As per my understanding.
Step1) create Order_id
order_amount = 50000
order_currency = 'INR'
order_receipt = 'order_rcptid_11'
notes = {'Shipping address': 'Bommanahalli, Bangalore'} # OPTIONAL
obj = client.order.create(amount=order_amount, currency=order_currency, receipt=order_receipt, notes=notes)
then save order in databas
order_id = obj['id']
Orders(
id=order_id,
status="pending",
user=user,
razorpay_payment_id="",
razorpay_order_id="",
razorpay_signature="").save()
Step2 - Pass the order_id to the checkout page
<form action="https://www.example.com/payment/success/" method="POST">
<script
src="https://checkout.razorpay.com/v1/checkout.js"
data-key="YOUR_KEY_ID" // Enter the Test API Key ID generated from Dashboard → Settings → API Keys
data-amount="29935" // Amount is in currency subunits. Hence, 29935 refers to 29935 paise or ₹299.35.
data-currency="INR"//You can accept international payments by changing the currency code. Contact our Support Team to enable International for your account
data-order_id="order_CgmcjRh9ti2lP7"//Replace with the order_id generated by you in the backend.
data-buttontext="Pay with Razorpay"
data-name="Acme Corp"
data-description="A Wild Sheep Chase is the third novel by Japanese author Haruki Murakami"
data-image="https://example.com/your_logo.jpg"
data-prefill.name="Gaurav Kumar"
data-prefill.email="gaurav.kumar#example.com"
data-theme.color="#F37254"
></script>
<input type="hidden" custom="Hidden Element" name="hidden">
</form>
Step3: Get the reponse on payment completed
{
"razorpay_payment_id": "pay_29QQoUBi66xm2f",
"razorpay_order_id": "order_9A33XWu170gUtm",
"razorpay_signature": "9ef4dffbfd84f1318f6739a3ce19f9d85851857ae648f114332d8401e0949a3d"
}
Now We have to verify this.
But here we dont know this response is for which order_id as per this image.
Because i have seen someone using the below to retrieve the order
Orders.objects.get(order_id = razorpay_order_id)
but this contradicts with the notes in the above image.
If order_id is not same razorpay_order_id then the only way to retrieve the order is it to include it in the callback url like /successs/order_id
So how to do this the right way
Also one more confusing thing i found is that the python library razorpay is different from the docs
And what the docs say:
and again another confusion is the docs says we can use the python module
In step 1, with obj = client.order.create() and obj['id'] what you are getting is the order_id, and you have to save it in the DB corresponding to the Order.
We can blindly trust this created order_id since this is created in our server.
And on completing the checkout process of the order, the Razorpay returns razorpay_order_id, this will be the same as our order_id unless someone manipulated it. That's why the documentation says:
Do not use the razorpay_order_id "returned by the Checkout"
What does it actually mean is Do not use the razorpay_order_id "returned by the Checkout" directly in the
client.payment.capture(response['razorpay_payment_id'], ... )
without any validations or cross-checking with our previously created order_id
How to return the order?
Since we have already saved our Order with the order_id,
we can cross-check the razorpay_order_id with our order_id like in the example you mentioned.
trusted_order = Orders.objects.filter(order_id=razorpay_order_id)
if there exists a trusted_order that is not previously paid then we are safe to use razorpay_payment_id.

QuickBooks Desktop Invoice Integration and InvoiceGroupLine Limitations

I have been Integrating Invoice module of Quickbooks Desktop Enterprise with an application using "qbxml", i encountered that with InvoiceLine i can send many fields including custom fields, But when it comes to InvoiceGroupLine i can't send the following which i need too:
1.Service Date field;
2.Other1;
3.Other2.
(all of the above mentioned fields to be added at the last row of GroupItem where description of it is placed as shown in picture below.)
Also attached picture shows the custom field called "Employee" was populated at the first line of this, which should be at the bottom where the last description is.
Secondly, you can see i was unable to pass through 'service date' and 'other1' which is 'Patient' and 'other2' which is 'MR Number' fields for GroupItem.
The reason why i asked about population on the bottom is because, only the last line of GroupItem copies to Print/Print Preview of Invoices in Quickbooks.
How can i able to achieve my goal of sending over these fields as i mentioned above to QuickBooks to their respective places/positions and fields? thanks.

Amazon Product Advertising API: Get Average Customer Rating

When using Amazon's web service to get any product's information, is there a direct way to get the Average Customer Rating (1-5 stars)? Here are the parameters I'm using:
Service=AWSECommerceService
Version=2011-08-01
Operation=ItemSearch
SearchIndex=Books
Title=A Game of Thrones
ResponseGroup=Large
I would expect it to have a customer rating of 4.5 and total reviews of 2177. But instead I get the following in the response.
<CustomerReviews><IFrameURL>http://www.amazon.com/reviews/iframe?...</IFrameURL></CustomerReviews>
Is there a way to get the overall customer rating, besides for reading the <IFrameURL/> value, making another HTTP request for that page of reviews, and then screen scraping the HTML? That approach is fragile since Amazon could easily change the reviews page structure which would bust my application.
You can scrape from here. Just replace the asin with what you need.
http://www.amazon.com/gp/customer-reviews/widgets/average-customer-review/popover/ref=dpx_acr_pop_?contextId=dpx&asin=B000P0ZSHK
As far as i know, Amazon changed it's API so its not possible anymore to get the reviewrank information. If you check this Link the note sais:
As of November 8, 2010, only the iframe URL is returned in the request
content.
However, testing with the params you used to get the Iframe it seems that now even the Iframe dosn't work anymore. Thus, even in the latest API Reference in the chapter "Motivating Customers to Buy" the part "reviews" is compleatly missing.
However: Since i'm also very interested if its still possible somehow to get the reviewrank information - maybe even not using amazon API but a competitors API to get review rank informations - i'll set up a bounty if anybody can provide something helpful on that. Bounty will be set in this topic in two days.
You can grab the iframe review url and then use css to position it so only the star rating shows. It's not ideal since you're not getting raw data, but it's an easy way to add the rating to your page.
Sample of this in action - http://spamtech.co.uk/positioning-content-inside-an-iframe/
Here is a VBS script that would scrape the rating. Paste the code below to a text file, rename it to Test.vbs and double click to run on Windows.
sAsin = InputBox("What is your ASIN?", "Amazon Standard Identification Number (ASIN)", "B000P0ZSHK")
if sAsin <> "" Then
sHtml = SendData("http://www.amazon.com/gp/customer-reviews/widgets/average-customer-review/popover/ref=dpx_acr_pop_?contextId=dpx&asin=" & sAsin)
sRating = ExtractHtml(sHtml, "<span class=""a-size-base a-color-secondary"">(.*?)<\/span>")
sReviews = ExtractHtml(sHtml, "<a class=""a-size-small a-link-emphasis"".*?>.*?See all(.*?)<\/a>")
MsgBox sRating & vbCrLf & sReviews
End If
Function ExtractHtml(sHtml,sPattern)
Set oRegExp = New RegExp
oRegExp.Pattern = sPattern
oRegExp.IgnoreCase = True
Set oMatch = oRegExp.Execute(sHtml)
If oMatch.Count = 1 Then
ExtractHtml = Trim(oMatch.Item(0).SubMatches(0))
End If
End Function
Function SendData(sUrl)
Dim oHttp 'As XMLHTTP30
Set oHttp = CreateObject("Msxml2.XMLHTTP")
oHttp.open "GET", sUrl, False
oHttp.send
SendData = Replace(oHttp.responseText,vbLf,"")
End Function
Amazon has completely removed support for accessing rating/review information from their API. The docs mention a Response Element in the form of customer rating, but that doesn't work either.
Google shopping using Viewpoints for some reviews and other sources
This is not possible from PAPI. You either need to scrape it by yourself, or you can use other free/cheaper third-party alternatives for that.
We use the amazon-price API from RapidAPI for this, it supports price/rating/review count fetching for up to 1000 products in a single request.

How to obtain longitude and latitude for a street address programmatically (and legally)

Supposedly, it is possible to get this from Google Maps or some such service. (US addresses only is not good enough.)
The term you're looking for is geocoding and yes Google does provide this service.
New V3 API: http://code.google.com/apis/maps/documentation/geocoding/
Old V2 API: http://code.google.com/apis/maps/documentation/services.html#Geocoding
In addition to the aforementioned Google geocoding web service, there is also a competing service provided by Yahoo. In a recent project where geocoding is done with user interaction, I included support for both. The reason is I have found that, especially outside the U.S., their handling of more obscure locations varies widely. Sometimes Google will have the best answer, sometimes Yahoo.
One gotcha to be aware of: if Google really thinks they don't know where your place is, they will return a 602 error indicating failure. Yahoo, on the other hand, if it can peel out a city/province/state/etc out of your bad address, will return the location of the center of that town. So you do have to pay attention to the results you get to see if they are really what you want. There are ancillary fields in some results that tell you about this: Yahoo calls this field "precision" and Google calls it "accuracy".
If you want to do this without relying on a service, then you download the TIGER Shapefiles from the US Census.
You look up the street you're interested in, which will have several segments. Each segment will have a start address and end address, and you interpolate along the segment to find where on the segment your house number lies.
This will provide you with a lon/lat pair.
Keep in mind, however, that online services employ a great deal of address checking and correction, which you'd have to duplicate as well to get good results.
Also note that as nice as free data is, it's not perfect - the latest streets aren't in there (they might be in the data Google uses), and the streets may be off their real location by some amount due to survey inaccuracies. But for 98% of geocoding needs it works perfectly, is free, and you control everything so you're reducing dependencies in your app.
Openstreetmaps has the aim of mapping everything in the world, though they aren't quite there it's worth keeping tabs on as they provide their data under a CC license
However, many (most?) other countries are only mapped by gov't or services for which you need to pay a fee. If you don't need to geocode very much data, then using Google, Yahoo, or some of the other free worldwide mapping services may be enough.
If you have to geocode a lot of data, then you will be best served by leasing map data from a major provider, such as teleatlas.
-Adam
You could also try the OpenStreetMap NameFinder, which contains open source, wiki-like street data for (potentially) the entire world. NameFinder will cease to exist at the end of august, but Nominatim is its replacement.
Google requires you to show a Google map with their data, with a max of 2.5k (was 25k) HTTP requests per day. Useful but you have to watch usage.
They do have
http://groups.google.com/group/Google-Maps-API/web/resources-non-google-geocoders
(Google has since removed this. If you see a duplicate or cache, I'll link to that.)
...in which I found GeoNames which has both a downloadable db, free web service and a commercial web service.
Google's terms of service will let you use their geocoding API for free if your website is in turn free for consumers to use. If not you will have to get a license for the Enterprise Maps.
For use with Drupal and PHP (and easily modified):
function get_lat_long($address) {
$res = drupal_http_request('http://maps.googleapis.com/maps/api/geocode/json?address=' . $address .'&sensor=false');
return json_decode($res->data)->results[0]->geometry->location;
}
You can have a look at the Google Maps API docs here to get a start on this:
http://code.google.com/apis/maps/documentation/services.html#Geocoding
It also seems to be something that you can do for international addresses using Live Maps also:
http://virtualearth.spaces.live.com/blog/cns!2BBC66E99FDCDB98!1588.entry
You can also do this with Microsoft's MapPoint Web Services.
Here's a blog post that explains how:
http://www.codestrider.com/BlogRead.aspx?b=b5e8e275-cd18-4c24-b321-0da26e01bec5
R Code to get the latitude and longitude of a street address
# CODE TO GET THE LATITUDE AND LONGITUDE OF A STREET ADDRESS WITH GOOGLE API
addr <- '6th Main Rd, New Thippasandra, Bengaluru, Karnataka' # set your address here
url = paste('http://maps.google.com/maps/api/geocode/xml?address=', addr,'&sensor=false',sep='') # construct the URL
doc = xmlTreeParse(url)
root = xmlRoot(doc)
lat = xmlValue(root[['result']][['geometry']][['location']][['lat']])
long = xmlValue(root[['result']][['geometry']][['location']][['lng']])
lat
[1] "12.9725020"
long
[1] "77.6510688"
If you want to do this in Python:
import json, urllib, urllib2
address = "Your address, New York, NY"
encodedAddress = urllib.quote_plus(address)
data = urllib2.urlopen("http://maps.googleapis.com/maps/api/geocode/json?address=" + encodedAddress + '&sensor=false').read()
location = json.loads(data)['results'][0]['geometry']['location']
lat = location['lat']
lng = location['lng']
print lat, lng
Note that Google does seem to throttle requests if it sees more than a certain amount, so you do want to use an API key in your HTTP request.
I had a batch of 100,000 records to be geocode and ran into Google API's limit (and since it was for an internal enterprise app, we had to upgrade to their premium service which is $10K plus)
So, I used this instead: http://geoservices.tamu.edu/Services/Geocode/BatchProcess/ -- they also have an API. (the total cost was around ~200$)
You can try this in JavaScript for city like kohat
var geocoder = new google.maps.Geocoder();
var address = "kohat";
geocoder.geocode( { 'address': address}, function(results, status) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
alert(latitude+" and "+longitude);
}
});
In python using geopy PyPI used to get the lattitude,langitude,zipcode etc..
Here is the working sample code..
from geopy.geocoders import Nominatim
geolocator = Nominatim(user_agent="your-app-id")
location = geolocator.geocode("Your required address ")
if location:
print('\n Nominatim ADDRESS :',location.address)
print('\n Nominatim LATLANG :',(location.latitude, location.longitude))
print('\n Nominatim FULL RESPONSE :',location.raw)
else:
print('Cannot Find')
In Nominatim - Some addresses can't working, so i just tried MapQuest.
It returns correctly.
Mapquest provides free-plan 15000 transactions/month. It is enough for me.
Sample code:
import geocoder
g = geocoder.mapquest("Your required address ",key='your-api-key')
for result in g:
# print(result.address, result.latlng)
print('\n mapquest ADDRESS :',result.address,result.city,result.state,result.country)
print('\n mapquest LATLANG :', result.latlng)
print('\n mapquest FULL RESPONSE :',result.raw)
Hope it helps.
I know this is old question but google changing way to get latitude and longitude on regular based.
HTML code
<form>
<input type="text" name="address" id="address" style="width:100%;">
<input type="button" onclick="return getLatLong()" value="Get Lat Long" />
</form>
<div id="latlong">
<p>Latitude: <input size="20" type="text" id="latbox" name="lat" ></p>
<p>Longitude: <input size="20" type="text" id="lngbox" name="lng" ></p>
</div>
JavaScript Code
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap" async defer></script>
<script>
function getLatLong()
{
var address = document.getElementById("address").value;
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
document.getElementById("latbox").value=latitude;
var longitude = results[0].geometry.location.lng();
document.getElementById("lngbox").value=longitude;
}
});
}
</script>